题目描述
给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
1 -> 2 -> 3 -> 4 转换后为:2 -> 1 -> 4 -> 3
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
代码
c语言
/**
* 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 *fast = dummyHead;
struct ListNode *slow = dummyHead;
struct ListNode *slowPrev = dummyHead;
while (fast != NULL && fast->next != NULL) {
fast = fast->next->next;
if (fast == NULL) {
break;
}
slow = slow->next;
// 交换slow和fast
slow->next = fast->next;
slowPrev->next = fast;
fast->next = slow;
// 注意因为交换了,slow跑到了后面,
// fast后移移到slow,slowPrev移动到slow
fast = slow;
slowPrev = slow;
}
head = dummyHead->next;
free(dummyHead);
return head;
}