Java Program to reverse a Linked List ?
- A Linked list contains two things data and the address of the node each node is linked to the next node.
- There can be two solution to reverse a linked list in java.
Iterative
- Here we have three nodes i.e previousNode, currentNode and nextNode
- When currentNode is starting node, then previousNode will be null
- Assign currentNode.next to previousNode to reverse the link.
- In each iteration move currentNode and previousNode by 1 node.
![data- linked-list](https://cdn.wikitechy.com/interview-questions/java/iterative-method-linked-list.gif)
Sample Code in Java:
Output :
5 6 7 1 2
After reversing
2 1 7 6 5
Recursive Method:
- Divide the list in two parts – first node and rest of the linked list.
- Call reverse for the rest of the linked list.
- Link rest to first.
- Fix head pointer
![data- linked-list](https://cdn.wikitechy.com/interview-questions/java/reverse-linked-list-in-java.jpg)