-
Notifications
You must be signed in to change notification settings - Fork 0
/
200129-1.cpp
85 lines (79 loc) · 1.55 KB
/
200129-1.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// https://leetcode-cn.com/problems/reverse-linked-list-ii/
#include <cstdio>
#include <initializer_list>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* init(initializer_list<int> a) {
ListNode node(0);
ListNode* p = &node;
for (auto e : a) {
p->next = new ListNode(e);
p = p->next;
}
return node.next;
}
void release(ListNode* p) {
if (p) release(p->next);
delete p;
}
void print(ListNode* p, bool hasEndl = true) {
if (p) {
printf("%d ", p->val);
if (p->next) print(p->next, false);
}
if (hasEndl) printf("\n");
}
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode node(0);
node.next = head;
ListNode* p = &node;
for (int i = 1; i < m; ++i) p = p->next;
ListNode* a = p;
ListNode* b = p->next;
a->next = NULL;
p = b;
for (int i = m; i <= n; ++i) {
ListNode* next = p->next;
p->next = a->next;
a->next = p;
p = next;
}
b->next = p;
return node.next;
}
};
int main()
{
Solution s;
{
ListNode* p = init({1,2,3,4,5});
p = s.reverseBetween(p, 2, 4);
print(p);
release(p); // answer: 1->4->3->2->5->NULL
}
{
ListNode* p = init({1,2,3,4,5});
p = s.reverseBetween(p, 1, 5);
print(p);
release(p); // answer: 5->4->3->2->1->NULL
}
{
ListNode* p = init({1,2,3,4,5});
p = s.reverseBetween(p, 2, 3);
print(p);
release(p); // answer: 5->4->3->2->1->NULL
}
{
ListNode* p = init({1});
p = s.reverseBetween(p, 1, 1);
print(p);
release(p); // answer: 5->4->3->2->1->NULL
}
return 0;
}