首页 > 其他 > 详细

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

时间:2021-07-13 17:16:55      阅读:8      评论:0      收藏:0      [点我收藏+]

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;
    }
}

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!