0

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 + " ");
}
user3015224
  • 27
  • 2
  • 5

1 Answers1

-1

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

Community
  • 1
  • 1
Biswajit_86
  • 3,661
  • 2
  • 22
  • 36
  • This prints first, not last. The idea is to print things in reverse order; if you print before you recurse, you're printing them in insertion order. – Makoto Jul 25 '14 at 00:24
  • Yes I understand that. I am trying to debug if you have a circular linked list or if you are just running out of memory – Biswajit_86 Jul 25 '14 at 00:27