var swapPairs = function(head) {
if(head == null || head.next == null){
return head;
}
// 获得第 2 个节点
let next = head.next;
// next.next = head.next.next
// 第1个节点指向第 3 个节点,并从第3个节点开始递归
head.next = swapPairs(next.next);
// 第2个节点指向第 1 个节点
next.next = head;
// 或者 [head.next,next.next] = [swapPairs(next.next),head]
return next;
};
作者:Alexer-660
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/solution/24-liang-liang-jiao-huan-lian-biao-zhong-de-jie--7/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
// 第1个节点指向第 3 个节点,并从第3个节点开始递归
head.next = swapPairs(next.next);
其中这一行看不明白,这里的第3个节点是head.next还是next.next啊。。
// 第2个节点指向第 1 个节点
next.next = head;
而且这边的next.next是第二个节点吧。。怎么和上面的next.next对不上啊
从结果往上看比较好理解:
首先交换两个结点,那么返回的就是后面结点
所以返回next没有问题
然后要把前面的结点接到后面的结点
所以
最后,再拼接上 后面结果的交换结果