-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question42.cpp
53 lines (44 loc) · 1.11 KB
/
Question42.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
46
47
48
49
50
51
52
53
42 -> Reverse Linked List II
Solution :
class Solution {
public:
ListNode*reverse(ListNode*head){
if(head->next==NULL){
return head;
}
ListNode*newhead=reverse(head->next);
head->next->next=head;
head->next=NULL;
return newhead;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(left==right)return head;
ListNode*curr=head;
ListNode*prev=NULL;
int count=1;
while(count!=left){
prev=curr;
curr=curr->next;
count++;
}
ListNode* start=curr;
while(count!=right){
curr=curr->next;
count++;
}
ListNode*rest=curr->next;
curr->next=NULL;
ListNode*reversed=reverse(start);
if(prev){
prev->next=reversed;
}
ListNode*temp=reversed;
while(temp->next){
temp=temp->next;
}
temp->next=rest;
if(prev==NULL)
return reversed;
return head;
}
};