-
Notifications
You must be signed in to change notification settings - Fork 6
/
0092.cpp
55 lines (47 loc) · 1.24 KB
/
0092.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
// Solution 1 :-
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode* dummy = new ListNode(0);
dummy -> next = head;
ListNode* prev = dummy;
for(int i = 0; i < left - 1; i++)
prev = prev -> next;
ListNode* curr = prev -> next;
for(int i = 0; i < right - left; i++) {
ListNode* temp = curr -> next;
curr -> next = temp -> next;
temp -> next = prev -> next;
prev -> next = temp;
}
return dummy -> next;
}
};
// Solution 2 :-
class Solution {
public:
ListNode *reverseBetween(ListNode *head, int left, int right) {
if (left == right or !head)
return head;
ListNode *start{nullptr}, *prev{nullptr}, *curr{head};
int count{right - left};
while (curr and left--) {
start = prev;
prev = curr;
curr = curr->next;
}
ListNode *begin{prev};
while (curr and count--) {
ListNode *next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
begin->next = curr;
if (start) {
start->next = prev;
return head;
}
return prev;
}
};