• Post Reply Bookmark Topic Watch Topic
  • New Topic

Reverse linked list  RSS feed

 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I am having some trouble getting this code to do what I intend to. I am trying to reverse the list on which this method is called and return the new head.



For a sample input 1->2->3->4, this code gives 4->1. I suspect this line of code has something to do with it but I may be wrong. I wasn't really comfortable having that line there but I was hoping it would set the last node of the reversed list to null. Please help.
 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think instead of doing I should ideally be doing but I don't know how to keep track of that previous value in a recursive method.
 
Knute Snortum
Sheriff
Posts: 4289
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it have to be recursive? I would think iterative would work just fine.

If it needs to be recursive, maybe you could pass the previous node into the method, with null being the edge case.
 
Prasanna Raman
Ranch Hand
Posts: 410
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for responding, Knute. I already did it iteratively; I am just trying to get some practice using recursion. This is my iterative solution.Please take a look and see if I can make any improvements here.

For the recursive version, I got the same idea that you suggested as well. Using another parameter to the method, however I wanted to confirm that's the best of doing it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!