-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc92.cpp
More file actions
53 lines (42 loc) · 1.15 KB
/
lc92.cpp
File metadata and controls
53 lines (42 loc) · 1.15 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
#include <vector>
#include <iostream>
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) {
ListNode* node = head;
ListNode* leftnode = NULL;
std::vector<int> stack;
for(int i=1; i<=right; i++) {
if (left == i) {
leftnode = node;
}
if (left <= i && i <= right) {
stack.push_back(node->val);
}
node = node->next;
}
while(leftnode && !stack.empty()) {
int v = stack.back();
stack.pop_back();
leftnode->val = v;
leftnode = leftnode->next;
}
return head;
}
};
int main() {
Solution s;
ListNode * node = s.reverseBetween(new ListNode(1, new ListNode(2, new ListNode(3, NULL))),1,2);
while(node) {
std::cout << node->val << " ";
node = node->next;
}
std::cout << std::endl;
}