-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedListII.cpp
More file actions
42 lines (42 loc) · 859 Bytes
/
Copy pathReverseLinkedListII.cpp
File metadata and controls
42 lines (42 loc) · 859 Bytes
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
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *cur = head;
ListNode *prev = NULL;
ListNode *next = NULL;
ListNode *first = NULL;
ListNode *second = NULL;
n -= m;
m--;
while (m-- > 0) {
prev = cur;
first = cur;
cur = cur->next;
}
prev = cur;
second = cur;
cur = cur->next;
while (n-- > 0) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
second->next = cur;
if (first)
first->next = prev;
else
head = prev;
return head;
}
};