-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path92.Reverse Linked List II.cpp
More file actions
39 lines (34 loc) · 935 Bytes
/
92.Reverse Linked List II.cpp
File metadata and controls
39 lines (34 loc) · 935 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
/**
* 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 *head_head = new ListNode(0);
head_head->next = head;
ListNode *beg = head_head;
for (int i = 1; i < m; ++i) {
beg = beg->next;
}
if (m == n) {
return head;
}
ListNode *node = beg->next, *end = beg->next;
for (int i = m; i <= n; ++i) {
ListNode *tmp = node->next;
ListNode *beg_next = beg->next;
beg->next = node;
node->next = beg_next;
node = tmp;
}
end->next = node;
head = head_head->next;
delete head_head;
return head;
}
};