-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLC-(M)-Reverse Linked List.cpp
70 lines (45 loc) · 1.37 KB
/
LC-(M)-Reverse Linked List.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Given the head of a singly linked list and two integers left and right where left <= right,
// reverse the nodes of the list from position left to position right, and return the reversed list.
class Solution {
public:
ListNode* reverse(ListNode* root){
ListNode* prev=NULL;
ListNode* curr= root;
ListNode* nex=NULL;
while(curr!=NULL){
nex=curr->next;
curr->next=prev;
prev=curr;
curr=nex;
}
return prev;
}
ListNode* reverseBetween(ListNode* head, int left, int right) {
if(head==NULL || left>=right) return head;
int lefty=left;
right-=left;
ListNode* temp = new ListNode(-1);
ListNode* start=head;
while(start!=NULL && --left){
temp=start;
start=start->next;
}
ListNode* start2=start;
while( start2!=NULL && right-- ){
start2=start2->next;
}
ListNode* endpoint=NULL;
if(start2!=NULL) {
endpoint=start2->next;
start2->next=NULL;
}
temp->next= reverse(start);
ListNode* point =temp->next;
while(temp->next!=NULL){
temp=temp->next;
}
if(temp!=NULL) temp->next= endpoint;
if(lefty==1) return point;
return head;
}
};