-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0092-reverse-linked-list-ii.cpp
More file actions
34 lines (31 loc) · 951 Bytes
/
0092-reverse-linked-list-ii.cpp
File metadata and controls
34 lines (31 loc) · 951 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
/*
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.
Time complexity: O(n)
Space complexity: O(1)
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy = new ListNode();
dummy->next = head;
int i=0;
ListNode* leftConnector = dummy,*temp = head;
while(i<left-1){
leftConnector = temp;
temp = temp->next;
i++;
}
ListNode* prev = NULL;
i=0;
while(i<right-left+1){
ListNode* store = temp->next;
temp->next = prev;
prev = temp;
temp = store;
i++;
}
leftConnector->next->next = temp;
leftConnector->next = prev;
return dummy->next;
}
};