题目
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
链表中节点的数目在范围 [0, 100] 内
0 <= Node.val <= 100
进阶:你能在不修改链表节点值的情况下解决这个问题吗?(也就是说,仅修改节点本身。)
思路
- 三指针交换法,类似于翻转链表
代码演示1
- 迭代法
struct ListNode* swapPairs(struct ListNode* head){
struct ListNode *tm, cur;
cur.next = head;
tm = &cur;
while (tm->next != NULL && tm->next->next != NULL) {
struct ListNode *p1 = tm->next, *p2 = tm->next->next;
tm->next = p2;
p1->next = p2->next;
p2->next = p1;
tm = p1;
}
return cur.next;
}
运行效果
- 递归法
struct ListNode* swapPairs(struct ListNode* head) {
if (head == NULL || head->next == NULL) return head; //递归出口
struct ListNode *tm = head->next;
head->next = swapPairs(tm->next);
tm->next = head;
return tm;
}