leetcode_swap_nodes_in_pairs

难度:Easy

解题思路:先在纸上画图。

dummy -> 1 -> 2 -> 3 -> 4

dummy    1 -> 2 -> 3 -> 4
  |           ^
  |___________|


         |---------|
         |         ^
dummy    1    2 -> 3 -> 4
  |           ^
  |___________|

         |---------|
         |         ^
dummy    1 <- 2    3 -> 4
  |           ^
  |___________|

代码如下:

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
/**
* 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* dummy = new ListNode(-1), *cur = dummy;
dummy->next = head;
while(cur->next != NULL && cur->next->next != NULL)
{
ListNode *first = cur->next;
ListNode *second = first->next;
cur->next = second;
first->next = second->next;
second->next = first;
cur = first;
}
return dummy->next;
}
};

运行结果:3ms,超过11.49%