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;
    }
    
}
相关推荐
kyriewen6 小时前
Anthropic 估值逼近万亿美元,Claude Sonnet 5 + Claude Science 一天两连发
前端·ai编程·claude
小徐_23337 小时前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼10 小时前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
泯泷10 小时前
第 2 篇:设计第一套字节码:Opcode、Instruction 与 Constant Pool
前端·javascript·安全
妙码生花10 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十五):优化细节、网络请求封装
前端·后端·ai编程
泯泷10 小时前
第 1 篇:从 1 + 2 开始:亲手写出第一台 JSVM
前端·javascript·安全
团团崽_七分甜10 小时前
Spring Boot 核心知识点总结
前端
lichenyang45311 小时前
从一个按钮开始,理解 ASCF 框架到底在做什么
前端
古夕11 小时前
第三方 SSO 接入实践:redirect_uri 编码、回调一致性与跨项目联调
前端·vue.js