-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0092.cpp
132 lines (120 loc) · 2.82 KB
/
0092.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int m, int n) {
// return func1(head, m, n);
return func2(head, m, n);
}
// One pass with stack
ListNode *func1(ListNode *head, int m, int n) {
if (head == NULL || head->next == NULL) {
return head;
}
if (m >= n) {
return head;
}
ListNode *tail1 = NULL;
ListNode *tail2 = NULL;
ListNode *curr = head;
stack<ListNode *> stk;
int sz = 1;
while (curr != NULL) {
if (sz == m - 1) {
tail1 = curr;
}
if (sz >= m && sz <= n) {
stk.push(curr);
}
curr = curr->next;
sz++;
}
tail2 = stk.top()->next;
if (tail1 == NULL && tail2 == NULL) {
return reverseList(head);
} else if (tail1 == NULL) {
stk.top()->next = NULL;
ListNode *new_head = reverseList(head);
head->next = tail2;
return new_head;
} else if (tail2 == NULL) {
tail1->next = reverseList(tail1->next);
return head;
} else {
stk.top()->next = NULL;
ListNode *next1 = tail1->next;
tail1->next = reverseList(tail1->next);
next1->next = tail2;
return head;
}
return NULL;
}
// No need use a extra stack
ListNode *func2(ListNode *head, int m, int n) {
if (head == NULL || head->next == NULL) {
return head;
}
if (m >= n) {
return head;
}
ListNode *start = NULL;
ListNode *start_pre = NULL;
ListNode *end = NULL;
ListNode *end_next = NULL;
ListNode *curr = head;
int sz = 1;
while (curr != NULL) {
if (sz == m - 1) {
start_pre = curr;
}
if (sz == m) {
start = curr;
}
if (sz == n) {
end = curr;
end_next = end->next;
}
curr = curr->next;
sz += 1;
}
// 1. all need reverse, same condition: n-m+1 == sz
if (start == head && end_next == NULL) {
return reverseList(head);
}
// 2. from head to end
if (start == head) {
end->next = NULL;
curr = reverseList(head);
head->next = end_next;
return curr; // or end
}
// 3. from start to tail
if (end_next == NULL) {
start = reverseList(start);
start_pre->next = start;
return head;
}
// 4. from start to end
end->next = NULL;
curr = reverseList(start);
start_pre->next = end;
start->next = end_next;
return head;
}
ListNode *reverseList(ListNode *head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *second = head->next;
ListNode *new_head = reverseList(second);
second->next = head;
head->next = NULL;
return new_head;
}
};