java - 使用递归时 return 语句的混淆

标签 java recursion

我正在使用递归在链表的末尾插入一个节点。该代码工作正常。但我对返回语句有点困惑。

一一梳理一下我的理解:

第一个 return 将返回一个新节点 head == null 并且该函数将完成 - 无事可做

第二个将返回在尾部创建的节点 - 无事可做

最后会在每次递归调用 insertNodeAtTail 时将所有节点放入堆栈。当调用第二次返回时 head.next == null。所有节点都将从堆栈中弹出,直到到达第一个节点。实际上是链表中的第一个节点(指向头部)。

我的理解对吗?

public Node insertNodeAtTail(Node head, int data) {
    if(head == null) {
    /* List is empty so just return the new node */
        Node node = new Node();
        node.data = data;
        node.next = null;
        return node;
    }
    else if (head.next == null) {
    /* We are at the end of the list so insert the new node */
        Node node = new Node();
        node.data = data;
        head.next = node;
        return head;
    }
    else {
    /* Travese the list by passing the next node in the list until next is NULL */
        insertNodeAtTail(head.next, data);
    }

    /* This will put all the head nodes on the stack and then pop them off at the end */ 
    return head;
 }

非常感谢您的任何建议,

最佳答案

就这么办

public Node insertNodeAtTail(Node head, int data) {
 if(head == null) {
    head = new Node(data);
 }
 else{
    head.next = insertNodeAtTail(head.next,data);
 }
 return head;
}

关于java - 使用递归时 return 语句的混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39718123/

相关文章:

java - Http 获取异常目标主机在 ICS 上不能为空

c++ - 将链递归插入内存失败

java - 打印堆栈内容的递归方法

C++ 递归查找数组的最小值

java - Git merge/pull 后使用 Maven 进行部分全新安装

java - 如何修复 java.lang.UnsupportedClassVersionError : Unsupported major. 次要版本

java - 如何禁用 JPanel 中的所有组件

java - 如何使用过滤器来衡量性能?

c++ - 使用递归的 BST 中序遍历

haskell - 为什么内衬会在此构造上窒息?