Skip to content
July 22, 2007 / Upnishad

How would you reverse a singly linked list in Java ?

Sometimes the solutions are not quite obvious. Search for an algorithm to reverse a singly linked list using Java and you wont find any good hits except for this code.

   public void reverse()
   {
       Node ln1, ln2, ln3, ln4;
       if(first==null)
          return;

       ln1=first;
       ln2= first.next;
       ln3=null;
       while(ln2 != null)
       {

            ln4 = ln2.next;
            ln1.next = ln3;
            ln3= ln1;
            ln1=ln2;
            ln2 =ln4;
       }

       first = ln1;
       ln1.next = ln3;

   }

 

This might not be a very intuitive solution at first sight but infact this is a very clever simulation of C/C++ pointers in Java. 

Technorati tags: , ,
Advertisements

One Comment

Leave a Comment
  1. nuwanb / Sep 26 2009 1:56 pm

    This is working fine.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: