简体   繁体   English

链表递归方法

[英]Linkedlist recursive method

I'm trying to write a recursive method that prints a linked list in reverse but I get a stackoverflow error. 我正在尝试编写一种递归方法,该方法以反向方式打印链表,但出现了stackoverflow错误。 The method should terminate when the last element of the array has been reached, and return control to the method that called it, and then that method will print and return to the one that called it and so forth. 该方法应在到达数组的最后一个元素时终止,并将控制权返回给调用它的方法,然后该方法将打印并返回到调用它的方法,依此类推。

public void print(Node node){
    if(node.next != null)
       print(node.next);

    System.out.println(" " + node.value + " ");
}

Convert your code into 将您的代码转换成

public void print(Node node){
   System.out.println(" " + node.value + " "); 
 if(node.next != null)
       print(node.next);   

}
  1. If it still fails with an exception , it means you have a cyclic linked list 如果仍然由于异常而失败,则意味着您有一个循环链表
  2. If it does not fail, it means you are filling up the default memory heap assigned to your application. 如果没有失败,则表示您正在填充分配给应用程序的默认内存堆。 You can try increasing the heap size to see if it resolves the problems 您可以尝试增加堆大小以查看是否可以解决问题

Once you figure out the issue, you can restore the original code.If you want info on how to increase heap size, check out this link 解决问题后,您可以还原原始代码。如果您需要有关如何增加堆大小的信息,请查看此链接

Increase heap size in Java 增加Java中的堆大小

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM