How to reverse elements of LikedList

In Previous post we have learned How Convert Array to LinkedList. Here we will see how to reverse linked list content in Java. We can reverse list in java using below methods

  1. Using Collections.reverse() method
  2. Using List.Set() Method

1. Using Collections.reverse() Method

In this method we will learn how to reverse elements of a linked list in java using collections . We can reverse list  in java with the help of reverse() method of collections. This method reverses the order of the elements in the given list.This method runs in linear time.                                                                    Syntax :

public static void reverse(List<?> list);

Parameter : It takes as parameter list whose elements are to be reversed.                                        Exception : It throws following exceptions.                                                            UnsupportedOperationException – if the specified list or its list-iterator does not support the set operation.

Let’s see example of collections.reverse() method

import java.util.Collections;
import java.util.LinkedList;

public class ReverseAllelement {

public static void main(String[] args) {

LinkedList<String> linkedList = new LinkedList<String>();

linkedList.add("Mumbai");
linkedList.add("Delhi");
linkedList.add("Noida");
linkedList.add("Gao");
linkedList.add("Patna");
//print linkedlist
System.out.println("Before Reverse Linklist is = "+linkedList);

//Reverses the order of the elements in the specified list.

Collections.reverse(linkedList);

System.out.println("After Reverse Linklist is = "+linkedList);

}
}

Output:

Before Reverse Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]

After Reverse Linklist is = [Patna, Gao, Noida, Delhi, Mumbai]

2. Using List.Set() Method

We can reverse linked list content using List.set() Method . We the help of set() method we can swap element of list. Let’s see example for this

import java.util.LinkedList;

public class LinkedListReverse {
	public static void main(String[] args) {
		LinkedList<String> linkedList = new LinkedList<String>();

		linkedList.add("Mumbai");
		linkedList.add("Delhi");
		linkedList.add("Noida");
		linkedList.add("Gao");
		linkedList.add("Patna");
		//print linkedlist
		System.out.println("Before Reverse Linklist is = "+linkedList);
		reverse(linkedList);
		System.out.println("After Reverse Linklist is = "+linkedList);
		
	}

	public static void reverse(LinkedList list) {
	    //swap first element with end element and so on
	    for(int i = 0, mid = list.size()/2, j = list.size() - 1; i < mid; i++, j--)
	        list.set(i, list.set(j, list.get(i)));//swap element
	}	
}

Output :

Before Reverse Linklist is = [Mumbai, Delhi, Noida, Gao, Patna]
After Reverse Linklist is = [Patna, Gao, Noida, Delhi, Mumbai]

A Guide To Java LinkedList

 

Leave a Reply

Your email address will not be published. Required fields are marked *

87 + = 95