Wednesday, 20 November 2013

Java has a built in functionality to reverse Linked List. This function is available in Collections class and the method name is reverse(). It is a static function so you can simply call it using Collections.reverse(yourLinkedList);

Output :

Original LL : [A, B, C, D]

Revered LL : [D, C, B, A]

This shows you are aware of Java APIs but ultimately interviewer will get to the logic part as of how this is exactly done. or to put it in other words how is the method Collections.reverse() exactly implemented?

You can view the source code to know the exact method but as far as our LinkedList reversal problem is concerned we do the following -

Output :

Original LL : [A, B, C, D]

Revered LL : [D, C, B, A]Note : LinkedList data structure in Java is in fact a doubly linked list and hence we could use previous() on the list iterator. If you look at the LinkedList class you will find Node structure as follows