Write a Java program to remove a specified element from a linked list


The Java code provided demonstrates how to remove a specified element from a linked list using the remove method.

  • The code defines a class named Remove_SpecifiedEle 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 specified element.
  • The fru_list.remove(3) statement is called to remove the element at index 3 in fru_list. In this example, the element at index 3 is "Banana".
  • The System.out.println statement is used to print the contents of fru_list after removing the specified element.
  • The output of the program will be the contents of fru_list printed before and after removing the specified element.

Source Code

import java.util.*;
public class Remove_SpecifiedEle
{
	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("Given linked list : " + fru_list);
		fru_list.remove(3);
		System.out.println("After Remove specified element : " + fru_list);
	}
}

Output

Given linked list : [Papaya, Mulberry, Apple, Banana, Cherry, Watermelon]
After Remove specified element : [Papaya, Mulberry, Apple, Cherry, Watermelon]

Example Programs