forked from kedebug/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseLinkedListII.cpp
More file actions
34 lines (32 loc) · 915 Bytes
/
ReverseLinkedListII.cpp
File metadata and controls
34 lines (32 loc) · 915 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
/**
* 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 prev_head(0);
prev_head.next = head;
ListNode *prev = &prev_head;
ListNode *current = head;
for (int i = 0; i < m - 1; i++) {
prev = prev->next;
current = current->next;
}
ListNode *end = current;
for (int i = m - 1; i < n; i++) {
ListNode *next = current->next;
current->next = prev->next;
prev->next = current;
current = next;
}
end->next = current;
return prev_head.next;
}
};