Reverse Singly Linked List Java

sammy333 picture sammy333 · Mar 24, 2014 · Viewed 108.1k times · Source

Can someone tell me why my code dosent work? I want to reverse a single linked list in java: This is the method (that doesnt work correctly)

public void reverseList(){
    Node before = null;
    Node tmp = head;
    Node next = tmp.next;
    while(tmp != null){
      if(next == null)
         return;
      tmp.next = before;
      before = tmp;
      tmp = next;
      next = next.next;
    }
}

And this is the Node class:

public class Node{
   public int data;
   public Node next;
   public Node(int data, Node next){
      this.data = data;
      this.next = next;
   }
}

On input 4->3->2->1 I got output 4. I debugged it and it sets pointers correctly but still I dont get why it outputs only 4.

Answer

Joop Eggen picture Joop Eggen · Mar 24, 2014
Node next = tmp.next;
while(tmp != null){

So what happens when tmp == null?

You almost got it, though.

Node before = null;
Node tmp = head;
while (tmp != null) {
    Node next = tmp.next;
    tmp.next = before;
    before = tmp;
    tmp = next;
}
head = before;

Or in nicer (?) naming:

Node reversedPart = null;
Node current = head;
while (current != null) {
    Node next = current.next;
    current.next = reversedPart;
    reversedPart = current;
    current = next;
}
head = reversedPart;

ASCII art:

        <__<__<__ __ : reversedPart    : head
                 (__)__ __ __
head :   current:      >  >  >