-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwapNodesinPairs.cpp
81 lines (74 loc) · 1.4 KB
/
SwapNodesinPairs.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
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return NULL;
if (head->next == NULL)
return head;
ListNode *p = head->next;
head->next = swapPairs(p->next);
p->next = head;
return p;
}
ListNode *reverse(ListNode *pre,ListNode *next)
{
ListNode *last = pre->next;
ListNode *cur = last->next;
while(cur != next)
{
last->next = cur->next;
cur->next = pre->next;
pre->next = cur;
cur = last->next;
}
return last;
}
ListNode *SwapPairs(ListNode *head)
{
if (head == NULL)
return NULL;
ListNode *Host = new ListNode(0);
ListNode *pre = Host;
Host->next = head;
int i = 0;
while(head)
{
i++;
if (i % 2 == 0)
{
pre = reverse(pre,head->next);
head = pre->next;
}
else
head = head->next;
}
return Host->next;
}
int main()
{
ListNode *l1 = new ListNode(2);
ListNode *l2 = new ListNode(3);
ListNode *l3 = new ListNode(4);
ListNode *l4 = new ListNode(5);
ListNode *l5 = new ListNode(1);
l5->next = l4;
l4->next = l3;
l3->next = l2;
l2->next = l1;
ListNode *p = SwapPairs(l5);
while(p != NULL)
{
cout << p->val << ' ';
p = p->next;
}
cout << endl;
return 0;
}