24. Swap Nodes in Pairs

题目

https://leetcode.com/problems/swap-nodes-in-pairs/description/

想法

比较简单,虽然没啥意思,但还是做一下

考虑头的变化,以及尾就没有问题了

答案

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode *p = head;
if (p == NULL || p->next == NULL)
return p;
p = head;
ListNode *q = head->next->next;
head = head->next;
head->next = p;
p->next = q;
while(q != NULL && q->next != NULL) {
p->next = q->next;
ListNode *tmp = q->next->next;
q->next = tmp;
p = p->next->next;
q = q->next;
}
return head;
}
};