我正在使用递归在链表的末尾插入一个节点。该代码工作正常。但我对返回语句有点困惑。
一一梳理一下我的理解:
第一个 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/