Objective: Reverse the given linked list.

Example:

```Input : ->30->25->20->15->10->5

Reversed : ->5->10->15->20->25->30```

NOTE : Click Reverse a Linked List – Part 2 to see the another implementation of this problem.

Approach:

Iterative:

• Create 3 nodes, currNode, PrevNode and nextNode.
• Initialize them as currNode = head; nextNode = null;prevNode = null;
• Now keep reversing the pointers one by one till currNode!=null.
```   while(currNode!=null){
nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
```
• At the end set head = prevNode;
• See Example:

Note: If Image above is not clear, either zoom your browser or right click on image and open in a new tab.

• Recursive Approach:
• Take 3 nodes as Node ptrOne,Node ptrTwo, Node prevNode
• Reverse the ptrOne and ptrTwo
• Make a recursive call for reverseRecursion(ptrOne.next,ptrTwo.next,null)

Complete Code:

Output:

```->30->25->20->15->10->5
Reverse Through Iteration
->5->10->15->20->25->30
___________________
Original Link List 2 : ->36->35->34->33->32->31
Reverse Through Recursion
->31->32->33->34->35->36

```

__________________________________________________
Top Companies Interview Questions..-

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

### 7 Responses

1. Aman Rustagi says:
2. Tom Grimberg says:

there is a tiny mistake of numbering in the second stage picture
sould be like before: prevNode = currNode; step 3
currNode = nextNode; step 4

3. iOSeTutorials (Sheldon) says:

can u really access prev node if it is a singly linked list?

• iOSeTutorials (Sheldon) says:

I think it should be as easy as:
while (currentNode.next != nil) {

}

4. Paul says:

The recursive recurse method is flawed. What if the linked list is empty or contains only 1 element? It crashes…

5. rahul1906 says:

Here is better way for recursion –

public void reverseRecursion(Node curnode,Node prevnode){
if(curnode == null){
System.out.println(“n Reverse Through Recursion”);
display(prevnode);
return;
}
Node nextnode = curnode.next;
curnode.next = prevnode;
prevnode = curnode;
curnode = nextnode;
reverseRecursion(curnode,prevnode);
}

6. Alejandro Casanas says:

for a video explanation check our this video https://www.youtube.com/watch?v=DKn7GaMVi8M

This site uses Akismet to reduce spam. Learn how your comment data is processed.