24. 两两交换链表中的节点

24. 两两交换链表中的节点 - 力扣(LeetCode)

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。1

思路

这道题目正常模拟就可以了。

建议使用虚拟头结点,这样会方便很多,要不然每次针对头结点(没有前一个指针指向头结点),还要单独处理。

做题时候记得先画图,按照图中指针指向的链路写代码就行。使用虚拟头节点的话,这个过程简单很多。注意一下,在交换完一次节点后,需要把虚拟头节点向后移动!一定要移动!

以下是c++实现代码:

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* pre = new ListNode;
if (pre == nullptr) {
return pre;
}
pre->next = head;
ListNode* cur = pre;
while (cur->next && cur->next->next){
ListNode* first = cur->next;
ListNode* third = cur->next->next->next;
cur->next = cur->next->next;
cur->next->next = first;
cur->next->next->next = third;
cur = cur->next->next;
}
head = pre->next;
return head;
}
};

c语言实现代码如下:

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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
typedef struct ListNode ListNode;
ListNode* pre = (ListNode*)malloc(sizeof(ListNode));
if (pre == NULL) {
return pre;
}
pre->next = head;
ListNode* cur = pre;
while ((cur->next)&& cur->next->next)
{
ListNode* temp1 = cur->next;//1
ListNode* temp = cur->next->next->next;//3
cur->next = cur->next->next;//cur point 2
cur->next->next = temp1; //2 point 1
temp1->next = temp;//1 point 3
cur = cur->next->next;
}
head = pre->next;
return head;
}