Print Singly linked list in reverse using recursion - Java -
hi having little trouble trying print singly linked list in reverse order using recursion. have looked @ examples method doesn't take parameters. want print out in following format:
input: [1, 2, 3, 4, 5] , output:[5, 4, 3, 2, 1]
first refers to first node in singly linked list , use stringbuilder
build list can return @ end.
this have far:
public string printreverse() { stringbuilder mystring = new stringbuilder("["); if (head != null) { // base case head = head.next; mystring.append(head.value); // line 406 mystring.append(", "); // line 407 printreverse(); // line 408 } mystring = mystring.append("]"); return mystring.tostring(); }
i following error:
exception in thread "main" java.lang.nullpointerexception @ myprog.sll$node.access$100(sll.java:445) @ myprog.sll.printreverse(sll.java:406) @ myprog.sll.printreverse(sll.java:408) @ myprog.sll.printreverse(sll.java:408) @ myprog.sll.printreverse(sll.java:408) @ myprog.sll.printreverse(sll.java:408) @ myprog.sllapp.mymethod(sllapp.java:198) @ myprog.sllapp.<init>(sllapp.java:37) @ myprog.sllapp.main(sllapp.java:26)
i don't see doing wrong, suspect may way call method on itself. can suggest may doing wrong , how may go fixing it?
thanks!
you on complicating things. lets @ pseudo code:
- initial node head
- if next null print blank (recursion termination condition)
- else recurse next node
- then print current node
in code, becomes:
public string printreverse() { return printreverse(head); } private string printreverse(node n) { return next == null ? "" : (printreverse(next) + n.value); }
it's 2 lines of code - see kiss.
regarding second private method, common public method of recursive implementation set ip call private recursive method appropriate initial state.
Comments
Post a Comment