24. Swap Nodes in Pairs

每日一题 2019 - 03 - 12


题目:

Given a linked list, swap every two adjacent nodes and return its head.

You may not modify the values in the list’s nodes, only nodes itself may be changed.

Example:

1
Given 1->2->3->4, you should return the list as 2->1->4->3.

解法:

这个题让我们交换链表中相邻的两个位置的元素(注:这里交换过的元素不再进行交换),所以思路其实很简单,就是设置两个指针,一前一后进行变换,但在变换的过程中注意:

  • 交换完成之后,要让两个指针同时往后移两个元素
  • 交换之前要判断当前指针的下一个指向是不是为空,防止访问无效内存空间

代码:

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
/**
* 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 * temp = head;
if( head == NULL || head -> next == NULL )
{
return head ;
}
ListNode * temt = head ;
temp = temp -> next ;
while(1)
{
int test = temp -> val ;
temp -> val = temt -> val;
temt -> val = test ;
if(temp -> next != NULL)
{
temt = temp ;
temp = temp -> next ;
if(temp -> next != NULL)
{
temt = temp ;
temp = temp -> next ;
}
else
{
break ;
}
}
else
{
break ;
}
}
return head ;
}
};
0%
undefined