-1

I am writing a LinkedList reverse method, in the main method, I am defining temp and calling reverse method (root contains the linked list)

Node temp=null;
r=a.reverse(root,temp);

public Node reverse(Node node,Node temp){
    if(node!=null){
        Node n=new Node();
        n.data=node.data;
        n.next=temp;
        temp=n;
        node=node.next;
        reverse(node,temp);
    }
    return temp;    
}

My rote contains 10,20,30,40,50` while I print Node returned by reverse method, I get the output.. o/p--- 10

Wesley Coetzee
  • 4,768
  • 3
  • 27
  • 45
Uraj Gogoi
  • 44
  • 5
  • I'm downvoting this, because it "does not show any research effort". Simply [searching for your title](https://stackoverflow.com/search?q=java+linked+list+reverse) turned up several already-answered questions on this topic. – Kevin J. Chase Oct 10 '17 at 20:00

1 Answers1

1

You dismissed the return of the call inside the function itself, and that's why the whole call is returning only the temp from the first call. This should work:

Node temp=null;
r=a.reverse(root,temp);

public Node reverse(Node node,Node temp) {
    if (node!=null){
        Node n=new Node();
        n.data=node.data;
        n.next=temp;
        temp=n;
        node=node.next;
        return reverse(node,temp); // Here now we return this result
    }
return temp;    
}

Also, I recommend you this question with some other reversing methods.

Good luck!

GusSL
  • 652
  • 7
  • 23