【发布时间】:2018-07-29 06:01:29
【问题描述】:
请对我温柔一点……我正在学习,需要一些帮助。我正试图围绕下面的链接列表方法。我以为我了解递归是如何工作的,但我在这里遗漏了一些东西。有人可以帮我理解这个方法的逻辑和完整的调用堆栈吗?我不知道这些项目是如何相加的……恐怕这里需要一些细节。我在其他地方寻求帮助,但其他示例似乎没有帮助。
/**
* 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;
}
}
【问题讨论】:
-
在纸上列出一份清单,然后按照自己的方式完成。这是我见过的最简单的递归示例。
-
哎呀,谢谢约翰的帮助。
-
我是否解释得不够清楚,以至于我不了解逻辑,并且我对此并不陌生?无论如何,感谢您的贡献。
标签: java recursion linked-list