【问题标题】:Recursion with linked lists for Java studentJava学生的链表递归
【发布时间】: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


【解决方案1】:

阅读评论。注释代码比引入 2 个临时变量更容易理解。要得到的一点是,在头部之后的列表的其余部分本身就是一个列表,而这个列表就是 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 .

【讨论】:

    猜你喜欢
    • 2021-05-03
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 2017-01-29
    • 1970-01-01
    相关资源
    最近更新 更多