24. 两两交换链表中的节点
题目连接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/
难度:中等
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
来源:力扣(LeetCode)
思路
- 使用一个虚拟头结点
dummyHead
进行模拟操作。然后分为四个步骤去移动指针
如图所示:
代码实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode* dummyHead = (struct ListNode* )malloc(sizeof(struct ListNode));//建立一个虚拟头节点
dummyHead ->next =head;
struct ListNode *cur = dummyHead;
while(cur->next && cur->next->next)
{
struct ListNode *temp = cur->next;//两个临时指针用来保存地址
struct ListNode *temp1 = cur->next->next->next;
cur->next = cur->next->next;//第一步
cur->next->next = temp;//第二步
cur->next->next->next = temp1;//第三步
cur = cur->next->next;//第四步
}
return dummyHead->next;
}