Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 90437c0

Browse files
committed
Create: 0092-reverse-linked-list-ii.cpp
1 parent b98cb25 commit 90437c0

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

cpp/0092-reverse-linked-list-ii.cpp

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
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.
3+
4+
Time complexity: O(n)
5+
Space complexity: O(1)
6+
*/
7+
class Solution {
8+
public:
9+
ListNode* reverseBetween(ListNode* head, int left, int right) {
10+
ListNode* dummy = new ListNode();
11+
dummy->next = head;
12+
13+
int i=0;
14+
ListNode* leftConnector = dummy,*temp = head;
15+
while(i<left-1){
16+
leftConnector = temp;
17+
temp = temp->next;
18+
i++;
19+
}
20+
ListNode* prev = NULL;
21+
i=0;
22+
while(i<right-left+1){
23+
ListNode* store = temp->next;
24+
temp->next = prev;
25+
prev = temp;
26+
temp = store;
27+
i++;
28+
}
29+
leftConnector->next->next = temp;
30+
leftConnector->next = prev;
31+
32+
return dummy->next;
33+
}
34+
};

0 commit comments

Comments
 (0)