力扣 24题 两两交换链表中的节点

时间:2021-07-13 17:16:55   收藏:0   阅读:9

Question 24-swap nodes in pairs

解题思路

简单递归,如果当前节点没有后继,就返回当前节点(因为没有节点和它组成 pair 了)。否则,使当前节点的后继为自己后继的后继,并让当前节点的原后继成为它的前驱。

代码

class Solution {
    public ListNode swapPairs(ListNode head) {

        if (null == head)   return null;
        if (null == head.next)  return head;

        head.next.next = swapPairs(head.next.next);

        ListNode next = head.next;
        head.next = next.next;
        next.next = head;

        return next;
    }
}

原文:https://www.cnblogs.com/scarecrow-wbl/p/15006731.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!