-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path92. Reverse Linked List II.cpp
58 lines (45 loc) · 1.05 KB
/
92. 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
/**
* 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) {
if(!head)
return nullptr;
if(m == n)
return head;
ListNode *cur = head;
ListNode *prev = nullptr;
ListNode *next = nullptr;
ListNode *onebeforem = nullptr;
ListNode *mth = nullptr;
int mcopy = m;
m--;
n--;
while(cur->next && m-- && n--) {
prev = cur;
cur = cur->next;
}
onebeforem = prev;
mth = cur;
while(cur && n--) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
if(onebeforem)
onebeforem->next = cur;
if(cur)
mth->next = cur->next;
cur->next = prev;
if (mcopy == 1)
head = cur;
return head;
}
};