0
// my print in normal order

public void printList()
    {   
        ListElem curr = head;

        while(curr != null)
        {
            System.out.print(curr.getData() + "->");
            curr = curr.getNext();
        }
    }

// my attempt to print in reverse order

public void printListRev()
    {   
        ListElem curr = head;

        if(curr == null) return;

        printListRev();

        System.out.print(curr.getData() + " ");
    }

Since this method doesn't accept any arguments, I'm not sure how to go about doing this recursively. I am trying to figure out how to print out the elements (strings) in a singly linked list.

Jack Owen
  • 1
  • 4
  • 2
    Can't you add an argument to `printListRev`? – Eran Nov 19 '19 at 15:09
  • Yes, but I am trying to do it without adding any – Jack Owen Nov 19 '19 at 15:11
  • if you can't add argument just create a private helper method – Wojtek Mlodzianowski Nov 19 '19 at 15:12
  • Is there a way without adding a private helper method? – Jack Owen Nov 19 '19 at 15:15
  • make curr a class variable – Jarlik Stepsto Nov 19 '19 at 15:16
  • there are many ways. But what for? Is it your requirement to not have any helper methods? Usually, that's how you do it if you want to have some public interface and recursion. Other ways which come to my mind: You can reverse the list and use your printList() method (or the same way). You can iterate through the list, put elements onStack and print while iterating through the stack. – Wojtek Mlodzianowski Nov 19 '19 at 15:20
  • 1
    Using recursion requires passing an argument. – Marlin Pierce Nov 19 '19 at 15:24
  • If you really want to do this based on recursion you should keep in mind that Java does not support "tail call optimization" and for a large linked list you will run out of Stack memory which results in the aptly named StackOverFlowError ;-) See also: https://blogs.oracle.com/saas-fusion-app-performance/how-to-set-stack-size-to-overcome-javalangstackoverflowerror and: https://stackoverflow.com/questions/53354898/tail-call-optimisation-in-java – JohannesB Nov 19 '19 at 15:36

2 Answers2

0

it is not that easy to do with a singly linked list, if it was a doubly linked list and you could manage to get last element (tail element), then following up with the reverse order would be easier, but as you are saying it is a singly linked list i suggest you to load all elements into an array in the function in reverse order and print it directly, this is a work around other wise it is not possible... this is my insight

pavan kumar
  • 823
  • 6
  • 15
0

Just iterate over your list and build a string by prepending data of each item:

public void printListRev()
    {   
        ListElem curr = head;
        String result = "";
        while(curr != null)
        {
            result = curr.getData() + "->" + result;
            curr = curr.getNext();
        }
        System.out.print(result);
    }
StephaneM
  • 4,779
  • 1
  • 16
  • 33