-
Notifications
You must be signed in to change notification settings - Fork 0
/
200916-1.cpp
87 lines (81 loc) · 1.51 KB
/
200916-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
86
87
// https://leetcode-cn.com/problems/odd-even-linked-list/
#include <iostream>
using namespace std;
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) {}
};
ListNode* init(initializer_list<int>&& a)
{
ListNode node(0);
ListNode* p = &node;
for (auto it = a.begin(); it != a.end(); ++it) {
p->next = new ListNode(*it);
p = p->next;
}
return node.next;
}
void print(ListNode* l)
{
for (ListNode* p = l; p; p = p->next) {
cout << p->val << " ";
}
cout << endl;
}
void release(ListNode* p)
{
if (p) {
release(p->next);
delete p;
}
}
class Solution {
public:
ListNode* oddEvenList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *a = NULL, *a2 = NULL, *b = NULL, *b2 = NULL;
int i = 0;
for (ListNode* p = head; p; p = p->next, ++i) {
if (i % 2 == 0) {
if (!a) {
a = a2 = p;
} else {
a2->next = p;
a2 = p;
}
} else {
if (!b) {
b = b2 = p;
} else {
b2->next = p;
b2 = p;
}
}
}
a2->next = b;
b2->next = NULL;
return a;
}
};
int main()
{
Solution s;
{
ListNode* p = init({1,2,3,4,5});
print(p); // origin: 1->2->3->4->5->NULL
s.oddEvenList(p);
print(p); // answer: 1->3->5->2->4->NULL
release(p);
}
{
ListNode* p = init({2,1,3,5,6,4,7});
print(p); // origin: 2->1->3->5->6->4->7->NULL
s.oddEvenList(p);
print(p); // answer: 2->3->6->7->1->5->4->NULL
release(p);
}
return 0;
}