-
Notifications
You must be signed in to change notification settings - Fork 0
/
24_swapNodesInPair.cpp
executable file
·71 lines (54 loc) · 1.06 KB
/
24_swapNodesInPair.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
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
void
showNode(ListNode *head) {
while (head) {
std::cout << head->val << std::endl;
head = head->next;
}
};
class Solution {
public:
static ListNode* swapNodeInPair(ListNode *head) {
// iterate
ListNode *cur = head, *next = NULL, *pre = NULL, *first = new ListNode(-1);
first->next = head;
pre = first;
while (cur && cur->next) {
next = cur->next;
cur->next = next->next;
next->next = cur;
pre->next = next;
pre = cur;
cur = cur->next;
}
return first->next;
// recurse
// if (NULL == head || NULL == head->next)
// return head;
// ListNode *next = head->next;
// head->next = swapNodeInPair(head->next->next);
// next->next = head;
// return next;
}
};
int
main(int argc, char const *argv[])
{
ListNode a(1);
ListNode b(2);
ListNode c(3);
ListNode d(4);
ListNode e(5);
a.next = &b;
b.next = &c;
c.next = &d;
d.next = &e;
showNode(&a);
showNode(Solution::swapNodeInPair(&a));
return 0;
}