Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
374 views
in Technique[技术] by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

next.next = head;

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

 head.next = swapPairs(next.next);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...