Reverse Linked List - Java

package excel;

public class ReverseLinkedList {

public static class List{
int value;
List next;

public List(int value){
this.value = value;
}

public String toString(){
List l = this;

String listInString = "";

while(l != null){
listInString += l.value + "-->";
l = l.next;
}
return listInString + "tail";
}
}

public static void main(String args[]) {
List l = new List(1);
l.next = new List(2);
l.next.next = new List(3);
l.next.next.next = new List(4);

System.out.println(l.toString());
System.out.println(reverse(l).toString());
}

public static List reverse(List l){
if(l == null || l.next == null) return l;

List remainingReverseList = reverse(l.next);
List cur = remainingReverseList ;
while(cur.next != null) cur = cur.next;
cur.next = l;

l.next = null;
return remainingReverseList ;
}
}


input: 1-->2-->3-->4-->Tail
output: 4-->3-->2-->1-->Tail

Explanation:
reverse(1-->2-->3-->4); l = 1-->2-->3-->4 ==> cur = 4-->3-->2-->1....rem = 4-->3-->2-->1
     |
rem = reverse(2-->3-->4) ; l = 2-->3-->4 ==> cur = 4-->3-->2 .....rem = 4-->3-->2
               |
           rem = reverse(3-->4) ;  l = 3-->4 ==> cur = 4-->3 .......rem = 4-->3
                          |
                       rem = reverse(4) = 4

Comments

Popular posts from this blog

public vs protected vs default access modifiers - Java

Class, Reference and Object