Home » Link Lists(Nuts & Bolts of CS) » Reverse Link List

Basically there are two methods of reversing a linked list – iterative and recursive. Lets discuss the iterative method :
Logic: Iterate trough the linked list. In loop, change next to prev, prev to current and current to next.

This is simple and has the following complexity :
Time Complexity: O(n)
Space Complexity: O(1)

```<pre><code>private static void reverseIterative()
{
Node prev=null;
Node next=null;
while(current != null)
{
next = current.next;
current.next = prev;
prev = current;
current = next;
}
}</code></pre>
```

here is the code for both forward and reverse manner.

```public class LinkedListUtils
{
{
Object data;

{
this.data = data;
this.next = next;
}
}
public void addFirst( Object data )
{
}
/**
* Prints the linked-list by traversing it forwards.
*/
public static void print( LinkedListNode node ) {
if( node != null ) { // print till it doesnt find null values.
System.out.print( node.data + " " ); // print 15 first then node.next and so on.
print( node.next ); // instead of node=node.next and cursor = head directly fun. call can also be used
} // called without using temporary node(resursion..)

// this can also be used , but for understanding using this method here recursion example of function
// for( LinkedListNode cursor = node; cursor != null; cursor = cursor.next ) {
// System.out.print(cursor.data +" " );
// }

}
/**
* Prints the linked-list by traversing it backwards (in reverse).
*/
public static void printReverse( LinkedListNode node ) {
if( node != null ) {
printReverse( node.next ); // node = node.next
System.out.print( node.data + " " );
}
}

/**
* Test Method
*/
public static void main( String[ ] args ) {

// Initialize and populate the linked-list
for( int i = 0; i < 16; i++ ) {
}

System.out.println( "Forwards: " );

// Print the linked-list backwards (in reverse)
System.out.println( "\nBackwards: " );
}
}

```