[LeetCode] Reverse Linked List II

92. Reverse Linked List II

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.

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
queue<int> l, r;
stack<int> reverse;
ListNode* cur = head;
for(int i = 1; i < left; i++) {
l.push((int)cur->val);
cur = cur->next;
}
for(int i = left; i <= right; i++) {
reverse.push((int)cur->val);
cur = cur->next;
}
while(cur != nullptr) {
r.push((int)cur->val);
cur = cur->next;
}
ListNode* newHead = new ListNode(), *prev;
cur = newHead;
while(!l.empty()) {
cur->val = l.front();
cur->next = new ListNode();
prev = cur;
cur = cur->next;
l.pop();
}
while(!reverse.empty()) {
cur->val = reverse.top();
cur->next = new ListNode();
prev = cur;
cur = cur->next;
reverse.pop();
}
while(!r.empty()) {
cur->val = r.front();
cur->next = new ListNode();
prev = cur;
cur = cur->next;
r.pop();
}
prev->next = nullptr;
return newHead;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/16/PS/LeetCode/reverse-linked-list-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.