-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path142ReverseLinkedListII.cpp
More file actions
68 lines (51 loc) · 1.34 KB
/
Copy path142ReverseLinkedListII.cpp
File metadata and controls
68 lines (51 loc) · 1.34 KB
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
#include <iostream>
using namespace std;
// Definition
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
if (!head || left == right) return head;
ListNode dummy(0);
dummy.next = head;
ListNode* prev = &dummy;
// Move prev to (left - 1)
for (int i = 1; i < left; i++) {
prev = prev->next;
}
ListNode* curr = prev->next;
// Reverse part
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;
}
};
// Helper to print list
void printList(ListNode* head) {
while (head) {
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main() {
// Create list: 1->2->3->4->5
ListNode* head = new ListNode(1);
head->next = new ListNode(2);
head->next->next = new ListNode(3);
head->next->next->next = new ListNode(4);
head->next->next->next->next = new ListNode(5);
int left = 2, right = 4;
Solution obj;
head = obj.reverseBetween(head, left, right);
printList(head);
return 0;
}