-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24-swap-nodes-in-pairs.cpp
74 lines (59 loc) · 1.27 KB
/
24-swap-nodes-in-pairs.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
#include <vector>
#include <unistd.h>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
void swap_adj(ListNode* b, ListNode* p, ListNode* q){
if(b) b->next = q;
p->next = q->next;
q->next = p;
}
ListNode* swapPairs(ListNode* head) {
if(!head) return head;
if(!head->next) return head;
ListNode* b = NULL;
ListNode* p = head;
ListNode* hh = head->next;
while(p && p->next){
swap_adj(b, p, p->next);
b = p;
p = p->next;
}
return hh;
}
};
void gen_list(int* l, int len, ListNode* &h){
h = new ListNode(l[0]);
ListNode* p = h;
for(int i = 1; i < len; i++){
p->next = new ListNode(l[i]);
p = p->next;
}
}
int main(){
ListNode* h;
int l[4] = {1,2,3,4};
gen_list(l, 4, h);
Solution sol;
ListNode* n = sol.swapPairs(h);
while(n){
cout << n->val << " ";
n = n->next;
// sleep(1)
}
return 0;
}