[英]Recursion with linked lists for Java student
请在这里对我温柔...我正在学习并且可以使用一些帮助。 我正在尝试围绕下面的链表方法。 我以为我明白递归是如何工作的,但我在这里遗漏了一些东西。 有人能帮我理解这个方法的逻辑和完整的调用堆栈吗? 我无法弄清楚这些项目是如何加起来的……恐怕这里需要一定程度的细节。 我在其他地方寻求帮助,但其他示例似乎没有帮助。
/**
* Compute the sum of all the integers in a linked list of integers.
* @param head a pointer to the first node in the linked list
*/
public static int addItemsInList( IntNode head ) {
if ( head == null ) {
// Base case: The list is empty, so the sum is zero.
return 0;
} else {
// Recursive case: The list is non-empty. Find the sum of
// the tail list, and add that to the item in the head node.
// (Note that this case could be written simply as
//return head.item + addItemsInList( head.next );)
int listsum = head.item;
int tailsum = addItemsInList( head.next );
listsum = listsum + tailsum;
return listsum;
}
}
阅读评论。 注释代码比引入 2 个临时变量更容易理解。 要点是,List 的其余部分,跟在 head 后面,本身就是一个 List,而这个 List 就是 head.next。
/**
* Compute the sum of all the integers in a linked list of integers.
* @param head a pointer to the first node in the linked list
*/
public static int addItemsInList( IntNode head ) {
if ( head == null ) {
// Base case: The list is empty, so the sum is zero.
return 0;
} else {
// Recursive case: The list is non-empty. Find the sum of
// the tail list, and add that to the item in the head node.
return head.item + addItemsInList (head.next);)
}
}
可以像这样看到 4 个 Int 的列表:
List (8, List(7, List (3, List (2, List ()))))
最后一个元素是空列表,返回 0。
所以你有 head.item 8,然后添加 addItemsInList (7 ...)。 在那里您添加 7 并从 3... 添加到 2 ... 。
最后空List返回0,2+0=2,返回上次调用,加3+2返回5,其中7等待返回12,最后8加12返回20。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.