Reverse a LinkedList in Java
Last Updated :
21 Nov, 2022
Assuming you have gone through LinkedList in java and know about linked list. This post contains different examples for reversing a linked list which are given below: 1. By writing our own function(Using additional space): reverseLinkedList() method contains logic for reversing string objects in a linked list. This method takes a linked list as a parameter, traverses all the elements in reverse order and adds it to the newly created linked list. Algorithm: Step 1. Create a linked list with n elements Step 2. Create an empty linked list which will be used to store reversed elements Step 3. Start traversing the list from ‘n’ to ‘0’ and store the elements in the newly created list. Step 4. The elements will be stored in the following order: n, n-1, n-2, ……0 Step 5. Return the list to the caller and print it
Example:
Step 1: LL: 1 -> 2 -> 3 -> 4 -> 5 where 'LL' is the linked list with n elements
Step 2: 'Rev' is an empty linked list
Step 3: Start traversing, the below passes are the intermediate steps while traversing
1st pass: Rev: 5
2nd pass: Rev: 5 -> 4
3rd pass: Rev: 5 -> 4 -> 3
4th pass: Rev: 5 -> 4 -> 3 -> 2
5th pass: Rev: 5 -> 4 -> 3 -> 2 -> 1
Step 4: nth element of 'LL' is stored in 0th position of 'Rev',
n-1 element of LL is stored in 1st position of Rev and so on......
Step 5: Return Rev: 5 -> 4 -> 3 -> 2 -> 1 to the calling function.
Java
import java.util.*;
public class LinkedListTest1 {
public static void main(String[] args)
{
LinkedList<String> linkedli = new LinkedList<String>();
linkedli.add("Cherry");
linkedli.add("Chennai");
linkedli.add("Bullet");
System.out.print("Elements before reversing: " + linkedli);
linkedli = reverseLinkedList(linkedli);
System.out.print("\nElements after reversing: " + linkedli);
}
public static LinkedList<String> reverseLinkedList(LinkedList<String> llist)
{
LinkedList<String> revLinkedList = new LinkedList<String>();
for ( int i = llist.size() - 1 ; i >= 0 ; i--) {
revLinkedList.add(llist.get(i));
}
return revLinkedList;
}
}
|
Time Complexity: O(n) Space Complexity: O(n) NOTE: As we are using additional memory space for storing all the reversed ‘n’ elements, the space complexity is O(n).
Output:
Elements before reversing: [Cherry, Chennai, Bullet]
Elements after reversing: [Bullet, Chennai, Cherry]
2. By writing our own function(Without using additional space): In the previous example, a linked list is used additionally for storing all the reversed elements which takes more space. To avoid that, same linked list can be used for reversing. Algorithm: 1. Create a linked list with n elements 1. Run the loop for n/2 times where ‘n’ is the number of elements in the linkedlist. 2. In the first pass, Swap the first and nth element 3. In the second pass, Swap the second and (n-1)th element and so on till you reach the mid of the linked list. 4. Return the linked list after loop termination.
Example:
Input: 1 -> 2 -> 3 -> 4 -> 5
1st pass: (swap first and nth element)
5 -> 2 -> 3 -> 4 -> 1
2nd pass: (swap second and (n-1)th element)
5 -> 4 -> 3 -> 2 -> 1
3rd pass: (reached mid, Terminate loop)
5 -> 4 -> 3 -> 2 -> 1
Output: 5 -> 4 -> 3 -> 2 -> 1
Java
import java.util.*;
public class LinkedListTest2 {
public static void main(String[] args)
{
LinkedList<Integer> linkedli = new LinkedList<Integer>();
linkedli.add( new Integer( 1 ));
linkedli.add( new Integer( 2 ));
linkedli.add( new Integer( 3 ));
linkedli.add( new Integer( 4 ));
linkedli.add( new Integer( 5 ));
System.out.print("Elements before reversing: " + linkedli);
linkedli = reverseLinkedList(linkedli);
System.out.print("\nElements after reversing: " + linkedli);
}
public static LinkedList<Integer> reverseLinkedList(LinkedList<Integer> llist)
{
for ( int i = 0 ; i < llist.size() / 2 ; i++) {
Integer temp = llist.get(i);
llist.set(i, llist.get(llist.size() - i - 1 ));
llist.set(llist.size() - i - 1 , temp);
}
return llist;
}
}
|
Time Complexity: O(n/2) Space Complexity: O(1)
Output:
Elements before reversing: [1, 2, 3, 4, 5]
Elements after reversing: [5, 4, 3, 2, 1]
3. By using Collections class: Collections is a class in java.util package which contains various static methods for searching, sorting, reversing, finding max, min….etc. We can make use of the In-built Collections.reverse() method for reversing an linked list. It takes a list as an input parameter and returns the reversed list. NOTE: Collections.reverse() method uses the same algorithm as “By writing our own function(Without using additional space)”
Java
import java.util.*;
public class LinkedListTest3 {
public static void main(String[] args)
{
LinkedList<Integer> linkedli = new LinkedList<Integer>();
linkedli.add( new Integer( 1 ));
linkedli.add( new Integer( 2 ));
linkedli.add( new Integer( 3 ));
linkedli.add( new Integer( 4 ));
linkedli.add( new Integer( 5 ));
System.out.print("Elements before reversing: " + linkedli);
Collections.reverse(linkedli);
System.out.print("\nElements after reversing: " + linkedli);
}
}
|
Time Complexity: O(n/2) Space Complexity: O(1)
Output:
Elements before reversing: [1, 2, 3, 4, 5]
Elements after reversing: [5, 4, 3, 2, 1]
4.Reversing a linked list of user defined objects: An Employee class is created for creating user defined objects with employeeID, employeeName, departmentName as class variables which are initialized in the constructor. An linked list is created that takes only Employee(user defined) Objects. These objects are added to the linked list using add() method. The linked list is reversed using In-built reverse() method of Collections class. printElements() method is used to iterate through all the user defined objects in the linked list and print the employee ID, name and department name for every object.
Java
import java.util.*;
class Employee {
int empID;
String empName;
String deptName;
public Employee( int empID, String empName, String deptName)
{
this .empID = empID;
this .empName = empName;
this .deptName = deptName;
}
}
public class LinkedListTest4 {
public static void main(String[] args)
{
LinkedList<Employee> linkedli = new LinkedList<Employee>();
Employee emp1 = new Employee( 123 , "Cherry", "Fashionist");
Employee emp2 = new Employee( 124 , "muppala", "Development");
Employee emp3 = new Employee( 125 , "Bullet", "Police");
linkedli.add(emp1);
linkedli.add(emp2);
linkedli.add(emp3);
System.out.print("Elements before reversing: ");
printElements(linkedli);
Collections.reverse(linkedli);
System.out.print("\nElements after reversing: ");
printElements(linkedli);
}
public static void printElements(LinkedList<Employee> llist)
{
for ( int i = 0 ; i < llist.size(); i++) {
System.out.print("\n EmpID:" + llist.get(i).empID + ", EmpName:"
+ llist.get(i).empName + ", Department:" + llist.get(i).deptName);
}
}
}
|
Time Complexity: O(n/2) Space Complexity: O(1)
Output:
Elements before reversing:
EmpID:123, EmpName:Cherry, Department:Fashionist
EmpID:124, EmpName:muppala, Department:Development
EmpID:125, EmpName:Bullet, Department:Police
Elements after reversing:
EmpID:125, EmpName:Bullet, Department:Police
EmpID:124, EmpName:muppala, Department:Development
EmpID:123, EmpName:Cherry, Department:Fashionist
See reverse a linked list for reversing a user defined linked list.
Similar Reads
LinkedList in Java
Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and addr
13 min read
LinkedList set() Method in Java
The Java.util.LinkedList.set() method is used to replace any particular element in the linked list created using the LinkedList class with another element. This can be done by specifying the position of the element to be replaced and the new element in the parameter of the set() method. Syntax: Link
3 min read
LinkedList removeFirst() Method in Java
In Java, the removeFirst() method of the LinkedList class is used to remove and return the first element of the list. Example 1: Here, we use the removeFirst() method to remove the first element (head) of the LinkedList of Integers. [GFGTABS] Java // Java Program to demonstrate the // use of removeF
2 min read
LinkedList removeLast() Method in Java
In Java, the removeLast() method of LinkedList class is used to remove and return the last element of the list. Example 1: Here, we use the removeLast() method to remove and return the last element (tail) of the LinkedList. [GFGTABS] Java // java Program to demonstrate the // use of removeLast() in
2 min read
LinkedList get() Method in Java
In Java, the get() method of LinkedList is used to fetch or retrieve an element at a specific index from a LinkedList. Example 1: Here, we use the get() method to retrieve an element at a specified index. [GFGTABS] Java // Java Program to illustrate get() method import java.util.LinkedList; public c
2 min read
LinkedList addAll() Method in Java
In Java, the addAll() method of the LinkedList class is used to add all the elements of one collection to another. This method takes a Collection as an argument and adds all its elements to the end of the list. Example: Here, we use the addAll() method to add all the elements of one collection to an
3 min read
LinkedList addLast() Method in Java
In Java, the addLast() method of the LinkedList class is used to add an element at the end of the list. Syntax of LinkedList addLast() Method void addLast( E e) Parameter: e is the element you want to add at the end of the list.Return type: This method does not return any value.Example: Here, we use
1 min read
LinkedList getLast() Method in Java
In Java, the getLast() method in the LinkedList class is used to retrieve the last element of the list. Example 1: Here, we use the getLast() method to retrieve the last element of the list. [GFGTABS] Java // Java Program to Demonstrate the // use of getLast() in LinkedList import java.util.LinkedLi
2 min read
LinkedList push() Method in Java
In Java, the push() method of the LinkedList class is used to push an element at the starting(top) of the stack represented by LinkedList. This is similar to the addFirst() method of LinkedList. This method simply inserts the element at the first position or top of the LinkedList. Syntax of LinkedLi
1 min read
LinkedList addFirst() Method in Java
In Java, the addFirst() method of LinkedList, adds elements at the beginning of the list. All the existing elements moved one position to the right and the new element is placed at the beginning. Syntax of LinkedList addFirst() Method public void addFirst( E e) Parameters: E is the data type of elem
1 min read