-
Notifications
You must be signed in to change notification settings - Fork 0
/
191112-1.cpp
75 lines (69 loc) · 1.17 KB
/
191112-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
// https://leetcode-cn.com/problems/swap-nodes-in-pairs/
#include <cstdio>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void print(ListNode* p)
{
for (; p; p = p->next) {
printf("%d ", p->val);
}
printf("\n");
}
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if (!head || !head->next) return head;
ListNode node(0);
node.next = head;
ListNode* p = &node;
ListNode* q = head;
while (q && q->next) {
ListNode* tmp = p->next;
p->next = q->next;
q->next = p->next->next;
p->next->next = tmp;
p = q;
q = q->next;
}
return node.next;
}
};
ListNode* create(initializer_list<int> a)
{
ListNode* list = NULL;
ListNode* prev = NULL;
for (auto it = a.begin(); it != a.end(); ++it) {
ListNode* p = new ListNode(*it);
if (prev == NULL) {
list = p;
prev = p;
} else {
prev->next = p;
prev = p;
}
}
return list;
}
void destroy(ListNode* p)
{
while (p) {
ListNode* next = p->next;
delete p;
p = next;
}
}
int main()
{
Solution s;
ListNode* l = create({1, 2, 3, 4});
print(l);
l = s.swapPairs(l);
print(l);
destroy(l);
return 0;
}