forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-linked-list-ii.cpp
More file actions
38 lines (31 loc) · 861 Bytes
/
reverse-linked-list-ii.cpp
File metadata and controls
38 lines (31 loc) · 861 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
// Time: O(n)
// Space: O(1)
/**
* 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 dummy{0};
dummy.next = head;
auto *prev = &dummy;
for (int i = 0; i < m - 1; ++i) {
prev = prev->next;
}
auto *head2 = prev;
prev = prev->next;
auto *cur = prev->next;
for (int i = m; i < n; ++i) {
prev->next = cur->next; // Remove cur from the list.
cur->next = head2->next; // Add cur to the head.
head2->next = cur; // Add cur to the head.
cur = prev->next; // Get next cur.
}
return dummy.next;
}
};