-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReverse Linked List II.cpp
61 lines (57 loc) · 1.52 KB
/
Reverse Linked List II.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
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
if(!head || !head->next) return head;
if(m > n) return NULL;
ListNode *dummy = new ListNode(0);
dummy->next = head;
ListNode *node = dummy;
for(int i = 1; i < m; i++) {
if(node == NULL) return NULL;
else {
node = node->next;
}
}
ListNode *preNode = node;
ListNode *tailNode = node->next;
ListNode *nNode = cNode, *postNode = nNode->next;
for(int i = m; i < n; i++) {
if(postNode == NULL) return NULL;
ListNode *tmp = postsNode->next;
postNode->next = nNode;
nNode = postNode;
postNode = tmp;
}
preNode->next = nNode;
tailNode->next = postNode;
return dummy->next;
}
ListNode *reverseList(ListNode *head) {
if(!head || !head->next) return head;
ListNode *newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};
int main() {
ListNode *a = new ListNode(1);
a->next = new ListNode(2);
a->next->next = new ListNode(3);
a->next->next->next = new ListNode(4);
a->next->next->next->next = new ListNode(5);
Solution s;
ListNode *res = s.reverseBetween(a, 2, 4);
while(res) {
cout << res->val << endl;
res = res->next;
}
return 0;
}