LC24. 两两交换链表中的节点

代码随想录

java 复制代码
class Solution {
    // 举例子:假设两个节点 1 -> 2
    // 那么 head = 1; next = 2; next.next = null
    // 那么swapPairs(next.next),传入的是null,再下一次递归中直接返回null
    // 因此 newNode = null
    // 所以 next.next = head; => 2.next = 1; 2 -> 1
    //      head.next=  newNode; => 1.next = null; 1->null
    // 所以 2->1->null
    // 最终返回 next,即返回 2
    public ListNode swapPairs(ListNode head) {
        
        if(head == null || head.next == null)
            return head;

        ListNode next = head.next;

        ListNode newNode = swapPairs(next.next);


        next.next = head;

        head.next = newNode;

        return next;
    }
    
}
相关推荐
GISer小浪花努力上岸1 小时前
Java实现简易计算器功能(idea)
java·开发语言·intellij-idea
海海向前冲2 小时前
设计模式 -- 单例设计模式
java·开发语言·设计模式
就这样很好8802 小时前
排序算法总结
java·算法·排序算法
Random_index2 小时前
#名词区别篇:npx pnpm npm yarn区别
前端·npm
GDAL2 小时前
Puppeteer-Cluster:并行处理网页操作的新利器
运维·服务器·nodehtmltoimage
B.-2 小时前
Remix 学习 - 路由模块(Route Module)
前端·javascript·学习·react·web
weixin_486681142 小时前
C++系列-STL中find相关的算法
java·c++·算法
limengshi1383922 小时前
通信工程学习:什么是GFP通用成帧规范
服务器·网络·网络协议·学习·信息与通信
sone121382 小时前
计算机网络(第8版)第三章 数据链路层(3.4)
服务器·网络·计算机网络
学java的小菜鸟啊2 小时前
Java队列详细解释
java·开发语言·经验分享·python