简体   繁体   中英

Linkedlist recursive method

I'm trying to write a recursive method that prints a linked list in reverse but I get a stackoverflow error. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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