交换链表的节点


链表节点要这么画成图2这样的不要简单的画图1表示了。
代码如下

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
class Solution {
public:
ListNode * swapPairs(ListNode* head) {
auto p = head;
//no node
if (p == NULL) { return p; }

//swap first two nodes
if (p&&p->next) {
auto next = p->next;
p->next = p->next->next;
next->next = p;
head = next;//change head node
}
//only one node
else {
return p;
}

//swap rest nodes;
auto prev = head->next;
p = head->next->next;
while (p&&p->next){
auto next = p->next;
p->next = p->next->next;
next->next = p;
prev->next = next;
prev = p;
p = p->next;
}
return head;
}
};