-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswap-nodes-in-pairs.cc
60 lines (49 loc) · 947 Bytes
/
swap-nodes-in-pairs.cc
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
// https://oj.leetcode.com/problems/swap-nodes-in-pairs/
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode *res = head->next;
ListNode *prev = NULL;
ListNode *p = head;
while (p && p->next) {
ListNode *q = p->next;
ListNode *next = q->next;
if (prev) {
prev->next = q;
}
q->next = p;
p->next = next;
prev = p;
p = next;
}
return res;
}
};
int main(int argc, char const* argv[])
{
ListNode *a = new ListNode(1);
ListNode *b = new ListNode(2);
ListNode *c = new ListNode(3);
ListNode *d = new ListNode(4);
a->next = b;
b->next = c;
c->next = d;
Solution s;
ListNode *h = s.swapPairs(a);
while (h) {
cout << h->val << " ";
h = h->next;
}
cout << endl;
return 0;
}