Write a Java program to Remove the first occurrence and last occurrence of a given element in a LinkedList


The code demonstrates how to remove the first and last occurrences of an element from a LinkedList in Java. The FirstLast_Occurrence 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 statements are used to print the initial state of the list linked list before and after removing the first and last occurrences of the element "RUBY". The removeFirstOccurrence method is called on the list linked list with the argument "RUBY" to remove the first occurrence of "RUBY" from the linked list. If "RUBY" is found in the list, it will be removed, and the method will return true. If "RUBY" is not found in the list, the method will return false.

The removeLastOccurrence method is called on the list linked list with the argument "RUBY" to remove the last occurrence of "RUBY" from the linked list. If "RUBY" is found in the list, it will be removed, and the method will return true. If "RUBY" is not found in the list, the method will return false.

As a result, the initial state of the list linked list will be printed using the first System.out.println statement, the list after removing the first occurrence of "RUBY" will be printed using the second System.out.println statement, and the list after removing the last occurrence of "RUBY" will be printed using the third System.out.println statement.

Source Code

import java.util.*;
public class FirstLast_Occurrence
{
	public static void main(String[] args)
	{
		LinkedList<String> list = new LinkedList<String>();
		list.add("JAVA"); 
		list.add("CPP"); 
		list.add("PYTHON"); 
		list.add("RUBY"); 
		list.add("PHP"); 
		list.add("C"); 
		list.add("MYSQL"); 
		list.add("C#.NET"); 
		System.out.println(list);
 
		list.removeFirstOccurrence("RUBY");  //Removing the first occurrence
		System.out.println(list);   
 
		list.removeLastOccurrence("RUBY"); //Removing the last occurrence
		System.out.println(list);  
	}
}

Output

[JAVA, CPP, PYTHON, RUBY, PHP, C, MYSQL, C#.NET]
[JAVA, CPP, PYTHON, PHP, C, MYSQL, C#.NET]
[JAVA, CPP, PYTHON, PHP, C, MYSQL, C#.NET]

Example Programs