-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path092_Reverse_Linked_List_II.cpp
61 lines (58 loc) · 1.22 KB
/
092_Reverse_Linked_List_II.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
56
57
58
59
60
61
#include<iostream>
#include<vector>
#include<string>
#include<map>
using namespace std;
static const auto x=[](){
std::ios::sync_with_stdio(false);
std:cin.tie(nullptr);
return nullptr;
}();
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode* reverseBetween(ListNode* head, int m, int n)
{
ListNode *cur = head, *new_head = new ListNode(-1), *pre = new_head;
new_head->next = head;
int i = 1;
while( i < m)
{
pre = cur;
cur = cur->next;
i++;
}
while( i < n)
{
ListNode* to_move = cur->next;
cur->next = to_move->next;
to_move->next = pre->next;
pre->next = to_move;
i++;
}
return new_head->next;
}
};
int main(int argc, char const *argv[])
{
ListNode a(1), b(2), c(3), d(4), e(5);
// a.next = &b;
// b.next = &c;
// c.next = &d;
// d.next = &e;
c.next=&e;
Solution sol;
ListNode* res = sol.reverseBetween(&c, 1, 2);
while( res != NULL)
{
cout<<res->val<<"\t";
res =res->next;
}
return 0;
}