Write a Java program to remove first and last element from a linked list


The Java code provided demonstrates how to remove the first and last elements from a linked list using the removeFirst and removeLast methods.

  • The code defines a class named RemoveEle_FirstLast with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named fru_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Papaya", "Mulberry", "Apple", "Banana", "Cherry", and "Watermelon" are added to fru_list using the add method, which appends the elements to the end of the list.
  • The System.out.println statement is used to print the contents of fru_list before removing the first and last elements.
  • The fru_list.removeFirst() statement is called to remove the first element in fru_list, and the removed element is stored in the first_ele variable.
  • The System.out.println statement is used to print the first element that was removed from fru_list.
  • The fru_list.removeLast() statement is called to remove the last element in fru_list, and the removed element is stored in the last_ele variable.
  • The System.out.println statement is used to print the last element that was removed from fru_list.
  • The System.out.println statement is used to print the contents of fru_list after removing the first and last elements.
  • The output of the program will be the contents of fru_list printed before and after removing the first and last elements, as well as the first and last elements that were removed.

Source Code

import java.util.*;
public class RemoveEle_FirstLast
{
	public static void main(String[] args)
	{
		LinkedList<String> fru_list = new LinkedList<String>();
		fru_list.add("Papaya");
		fru_list.add("Mulberry");
		fru_list.add("Apple");
		fru_list.add("Banana");
		fru_list.add("Cherry");
		fru_list.add("Watermelon");
		System.out.println("The Given linked list : " + fru_list);
		Object first_ele = fru_list.removeFirst();
		System.out.println("First Element Removed : "+ first_ele);
		Object last_ele = fru_list.removeLast();
		System.out.println("Last Element Removed : "+ last_ele);
		System.out.println("The New linked list : " + fru_list);
	}
}

Output

The Given linked list : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
First Element Removed : Papaya
Last Element Removed : Watermelon
The New linked list : [Mulberry, Apple, Banana, Cherry]

Example Programs