[英]Confusion for return statements when using 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;
}
您只需将return放置在错误的位置,并返回相同的head元素即可。
else {
/* Travese the list by passing the next node in the list until next is NULL */
return insertNodeAtTail(head.next, data);
}
我从头写这个请检查。
是的,您的理解是正确的... :)
最后一次返回将导致问题,因为它将导致Head始终指向列表的倒数第二个节点。 您应该按照FallAndLearn的建议删除它。 如果我错了,请纠正我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.