给你一个链表,两两交换其中相邻的节点,并返回交换后链表的头节点。你必须在不修改节点内部的值的情况下完成本题(即,只能进行节点交换)。
示例 1:
输入:head = [1,2,3,4]
输出:[2,1,4,3]
示例 2:
输入:head = []
输出:[]
示例 3:
输入:head = [1]
输出:[1]
提示:
- 链表中节点的数目在范围 [0, 100] 内
- 0 <= Node.val <= 100
解题思路
1.首先交换当前两个节点:使用一个中间变量next存储第二个节点,第二个节点指向第一个节点
2.然后递归并连接两组节点:将第三个节点作为递归的参数,上一组尾部连接下一组头部(递归返回的值)
3.递归结束条件:当节点为null或节点的下一个节点为null时,无法交换
代码
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
// 如果为空或者只剩一个节点,不用再反转
if (head == null || head.next == null) {
return head;
}
// 第二个节点
const next = head.next;
// 将下一组头节点传入
// head指向下一组节点的头节点(经过交换后,head变成了尾部,所以head指向下一组开始)
head.next = swapPairs(next.next);
// 第二个节点指向head
next.next = head;
// next变成了头节点
return next;
};