Write a Java program to Remove the elements of a LinkedList from both the ends


The code demonstrates the removal of elements from both the head and the tail of a LinkedList in Java. The RemoveEle_FromBoth class contains a main method where a LinkedList object named list is created and populated with string elements using the add method.

The System.out.println statement is used to print the initial state of the list linked list. Then, several elements are removed from the head of the list linked list using the poll, pollFirst, remove, and removeFirst methods. These methods remove the elements from the head of the linked list, and the elements are removed in the order they were added.

The System.out.println statement is used to print the list linked list after removing elements from the head. Next, elements are removed from the tail of the list linked list using the pollLast and removeLast methods. These methods remove the elements from the tail of the linked list, and the elements are removed in the reverse order they were added.

The System.out.println statement is used to print the list linked list after removing elements from the tail. As a result, the list linked list will contain only the remaining elements after removing elements from both the head and the tail, as demonstrated by the printed output.

Source Code

import java.util.*;
public class RemoveEle_FromBoth
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.add("Apple"); 
		list.add("Mango");     
		list.add("Pineapple");  
		list.add("Cherry");    
		list.add("Guava");
		list.add("Banana");
		list.add("Watermelon"); 
		System.out.println(list);
		//Removing the elements from the head of the LinkedList 
		list.poll(); 
		list.pollFirst(); 
		list.remove(); 
		list.removeFirst(); 
		System.out.println(list); 
 
		//Removing elements from the end of the LinkedList 
		list.pollLast(); 
		list.removeLast();  
		System.out.println(list);
	}
}

Output

[Apple, Mango, Pineapple, Cherry, Guava, Banana, Watermelon]
[Guava, Banana, Watermelon]
[Guava]

Example Programs