关于leetcode两两交换节点的问题

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对不上啊

阅读 1.7k
1 个回答

从结果往上看比较好理解:

首先交换两个结点,那么返回的就是后面结点
所以返回next没有问题

然后要把前面的结点接到后面的结点
所以

next.next = head;

最后,再拼接上 后面结果的交换结果

 head.next = swapPairs(next.next);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题