You need to enable JavaScript to run this app. Java递归实现单链表反转的工作原理及代码疑问解析
优惠活动
大模型
产品
解决方案
定价
更多

Java递归实现单链表反转的工作原理及代码疑问解析

单链表反转递归实现的执行逻辑疑问

我正在查阅用于反转给定链表的递归实现函数,对应代码如下:

static Node reverse(Node head) {
    if(head == null) {
        return head;
    }

    // last node or only one node
    if(head.next == null) {
        return head;
    }

    Node newHeadNode = reverse(head.next);

    // change references for middle chain
    head.next.next = head;
    head.next = null;

    // send back new head node in every recursion
    return newHeadNode;
}

public static void main(String[] args) throws IOException {
    LinkedList llist = new LinkedList();
    llist.insertNode(20);
    llist.insertNode(4);
    llist.insertNode(15);
    llist.insertNode(85);
      
    Node llistReversed = reverse(llist.head);
    printSinglyLinkedList(llistReversed, " ");
}

按照代码的节点插入逻辑,最终构建完成的链表节点序列为:85 15 4 20

我原本认为,调用reverse方法完成处理后,head.next会指向值为15的第二个节点;基于这个认知,我完全无法理解这段代码是如何通过递归流程实现链表反转的。


内容的提问来源于stack exchange,提问作者monkeyBus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.25 04:36:03