题目描述
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
来源:力扣(LeetCode)
链接:leetcode-cn.com/problems/sw…
分析
链表交换,首先要找到它们的前驱,这里头节点也要交换,因此新建一个头结点指向现在的第一个节点。然后后面的节点互换,定义移动指针每次都位于要交换的两个节点的前驱。
实现
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head)
{
if (!head) {
return NULL;
}
if (head->next == NULL) {
return head;
}
// 相邻的交换,可以想到第一个节点也会交换,因此生成一个头节点用于返回结果
struct ListNode *h = (struct ListNode*)malloc(sizeof(struct ListNode));
h->val = 0;
h->next = head;
struct ListNode *tmp = h; // 游标tmp的后2个节点交换
while (tmp->next != NULL && tmp->next->next != NULL) {
struct ListNode *p1 = tmp->next;
struct ListNode *p2 = tmp->next->next;
tmp->next = p2;
p1->next = p2->next;
p2->next = p1;
tmp = p1;
}
return h->next;
}