-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_linked_list_ii.cpp
45 lines (44 loc) · 1.06 KB
/
reverse_linked_list_ii.cpp
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
45
/**
* 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) {
int gap = n - m + 1;
if(head){
ListNode* ret;
if(m == 1){
return reverse(head,gap);
}
else{
ListNode *tmp = head;
while(--m != 1){
tmp = tmp->next;
}
tmp->next = reverse(tmp->next, gap);
return head;
}
}
return nullptr;
}
ListNode* reverse(ListNode* head, int n){
if(head){
ListNode* cur = nullptr;
ListNode* tail = head;
while(n--){
ListNode *tmp = head;
head = head->next;
tmp->next = cur;
cur = tmp;
}
tail->next = head;
return cur;
}
return nullptr;
}
};