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;
    }
    
}
相关推荐
夏小花花2 分钟前
vue3 ref和reactive的区别和使用场景
前端·javascript·vue.js·typescript
outsider_友人A3 分钟前
前端也想写后端(3)中间件Middleware、管道Pipes、拦截器Interceptors
前端·node.js·nestjs
静Yu4 分钟前
Webpack 你到底在干什么!?
前端
掘金安东尼5 分钟前
前端周刊第427期(2025年8月4日–8月10日)
前端·javascript·面试
阿华的代码王国6 分钟前
【Android】适配器与外部事件的交互
android·xml·java·前端·后端·交互
mit6.8248 分钟前
[AI React Web] 包与依赖管理 | `axios`库 | `framer-motion`库
前端·人工智能·react.js
老虎062712 分钟前
JavaWeb前端(HTML,CSS具体案例)
前端·css·html
MacroZheng15 分钟前
还在用WebSocket实现即时通讯?试试MQTT吧,真香!
java·spring boot·后端
Mintopia18 分钟前
一个月速成 AI 工程师:从代码小白到智能工匠的修炼手册
前端·javascript·aigc
Mintopia21 分钟前
Next.js 全栈:接收和处理请求
前端·javascript·next.js