The process of reversing a linked list involves reversing the order of its data nodes. As a result, the last node becomes the head node, and the head node becomes the last node of the original linked list.
Suppose you have a linked list consisting of the following data nodes:
→ → → → →
Currently, the node with the value 1 is at the head of the list. The order of the nodes after the reversal process is shown below:
→ → → → →
After the reversal, the node with value 2 is at the head.
You can use the Collections.reverse()
method from the java.util
package to reverse the order of elements in a list.
The Collections.reverse()
method accepts the following parameter:
list
: This is the linked list that we want to reverse.The code snippet below shows how to reverse a linked list in Java:
import java.util.*;class Main{public static void main(String[] args){LinkedList<Integer> list = new LinkedList<Integer>();Scanner sc=new Scanner(System.in);list.add(3);list.add(25);list.add(14);list.add(16);list.add(9);System.out.println("Original linked list: " + list);Collections.reverse(list);System.out.println("Reversed linked list: " + list);}}
In line 1 we have imported the required package.
In line 2 we have initiated a class Main
.
In line 6 we have declared a linked list of int
data type.
In line 7 we have initiated an object as Scanner
class to use the methods available in it.
In lines 9 to 13 we have taken input of data from every node.
In line 15 we display the originally input linked list.
In line 16 we used the reverse()
method of the collections class from the java.util
package to reverse the list.
In line 17 we display the reversed linked list.