In this Linked List tutorial, we will see all about the reverse a linked list.
Example: If list contains 5 nodes
Input: 10 -> 20 -> 30 -> 40 -> 50
Output: 50 -> 40 -> 30 -> 20 -> 10
To reverse a linked list, there are two approaches:
- Iterative Approach
- Recursive Approach
Reverse a linked list using Iterative approach
public class Node {
int data;
Node next;
// Constructor
Node(int data) {
this.data = data;
this.next = null;
}
}
// Java program to reverse a linked list using Iterative approach
public class ReverseUsingIterativeApproachInSLL {
static Node reverseList(Node head) {
// Initialize three pointers: currNode, prevNode and nextNode
Node currNode = head, prevNode = null, nextNode;
while (currNode != null) {
nextNode = currNode.next;
currNode.next = prevNode;
// Move pointers one position ahead
prevNode = currNode;
currNode = nextNode;
}
// Return the head of reversed linked list
return prevNode;
}
// Method to print a linked list
static void printList(Node node) {
while (node != null) {
System.out.print(" " + node.data);
node = node.next;
}
}
public static void main(String[] args) {
// Create a linked list
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
// Linked list will be created like this
// 10 -> 20 -> 30 -> 40 -> 50
System.out.print("Original Linked list:");
printList(head);
head = reverseList(head);
System.out.print("\nReversed Linked List:");
printList(head);
}
}
Original Linked list: 10 20 30 40 50 Reversed Linked List: 50 40 30 20 10
Reverse a linked list using Recursive approach
// Java program to reverse a linked list using Recursive approach
public class ReverseUsingRecursiveApproachInSLL {
static Node reverseList(Node head) {
// If we reached the last node means list is empty,
// simply return the head of list
if (head == null || head.next == null)
return head;
// reverse the rest of linked list and put the first
// element at the end
Node rest = reverseList(head.next);
// Make the current head as last node of remaining
// linked list
head.next.next = head;
head.next = null;
return rest;
}
// Print a linked list
static void printList(Node node) {
while (node != null) {
System.out.print(" " + node.data);
node = node.next;
}
}
public static void main(String[] args) {
// Create a linked list
Node head = new Node(10);
head.next = new Node(20);
head.next.next = new Node(30);
head.next.next.next = new Node(40);
head.next.next.next.next = new Node(50);
// Linked list will be created like this
// 10 -> 20 -> 30 -> 40 -> 50
System.out.print("Original Linked list:");
printList(head);
head = reverseList(head);
System.out.print("\nReversed Linked List:");
printList(head);
}
}
Original Linked list: 10 20 30 40 50 Reversed Linked List: 50 40 30 20 10