-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_linked_list2.cpp
64 lines (58 loc) · 1.33 KB
/
reverse_linked_list2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* =====================================================================================
*
* Filename: reverse_linked_list2.cpp
*
* Description: 92. Reverse Linked List II.
*
* Version: 1.0
* Created: 04/11/19 03:39:11
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <cstdio>
#include <cstdlib>
struct ListNode {
int val;
ListNode* next;
explicit ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
// 1 <= left <= right <= n
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode fake(0);
ListNode* pre = &fake;
ListNode* cur = head;
fake.next = head;
while (--left > 0) {
pre = cur;
cur = cur->next;
right--;
}
pre->next = nullptr;
ListNode* last = cur;
ListNode* tmp = nullptr;
while (right > 0) {
tmp = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = tmp;
right--;
}
if (last != cur) {
last->next = cur;
}
return fake.next;
}
};
int main(int argc, char* argv[]) {
ListNode head(0);
auto* reverse = Solution().reverseBetween(&head, 0, 0);
return 0;
}