链表两两交换

递归大法好啊,遇事不决多画图,准没毛病。

  1. 把需要交换的两个节点的第一个节点传入递归
  2. 判断其自身是否为空(节点数偶数)、其下一节点是否为空(节点数奇数),任何一个为空都没有交换的意义。
  3. 接下来就是简单的交换了,把需要返回的节点返回即可。
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode second = head.next;
        ListNode third = second.next;
        second.next = head;
        head.next =  swapPairs(third);
        return second;
    }
}

本文作者:bokerr

本文链接:https://www.cnblogs.com/bokers/p/15591130.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   bokerr  阅读(48)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.