1. Introduction
In Java, a LinkedList can be reversed using various techniques such as using Collections.reverse(), traversing the list using ListIterator, or manually swapping elements. In this tutorial, we will explore how to reverse a LinkedList in Java using Collections.reverse() method.
2. Program Steps
1. Create and initialize a LinkedList.
2. Print the original LinkedList.
3. Reverse the LinkedList using Collections.reverse().
4. Print the reversed LinkedList.
3. Code Program
import java.util.Collections;
import java.util.LinkedList;
public class LinkedListReverseExample {
public static void main(String[] args) {
// Step 1: Create and initialize a LinkedList
LinkedList<String> animals = new LinkedList<>();
animals.add("Dog");
animals.add("Cat");
animals.add("Horse");
// Step 2: Print the original LinkedList
System.out.println("Original LinkedList: " + animals);
// Step 3: Reverse the LinkedList using Collections.reverse()
Collections.reverse(animals);
// Step 4: Print the reversed LinkedList
System.out.println("Reversed LinkedList: " + animals);
}
}
Output:
Original LinkedList: [Dog, Cat, Horse] Reversed LinkedList: [Horse, Cat, Dog]
4. Step By Step Explanation
Step 1: We create and initialize a LinkedList named animals with the elements "Dog", "Cat", and "Horse".
Step 2: We print the original LinkedList to the console.
Step 3: We use the Collections.reverse() method to reverse the order of the elements in the LinkedList. The reverse method is part of the Collections class and it reverses the order of the elements in the specified list.
Step 4: We print the reversed LinkedList to the console.
After executing the program, we can observe that the order of the elements in the LinkedList has been reversed successfully.