-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse_linked_list_2.cpp
More file actions
44 lines (44 loc) · 1.07 KB
/
Copy pathreverse_linked_list_2.cpp
File metadata and controls
44 lines (44 loc) · 1.07 KB
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
/**
* 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) {
ListNode* before_start = NULL, *after_end = NULL, *cur = head, *prev = NULL;
while (m - 1 && cur) {
--m;
--n;
before_start = cur;
cur = cur->next;
}
while (n - 1 && cur) {
--n;
cur = cur->next;
}
after_end = cur->next;
if (before_start == NULL) {
prev = head;
} else {
prev = before_start->next;
}
cur = prev->next;
prev->next = after_end;
while (cur != after_end) {
ListNode* old_next = cur->next;
cur->next = prev;
prev = cur;
cur = old_next;
}
if (before_start == NULL) {
head = prev;
} else {
before_start->next = prev;
}
return head;
}
};