Write a Java program to remove and return the first element of a linked list


The Java code provided demonstrates how to remove and return the first element from a linked list using the pop method.

  • The code defines a class named Remove_Return with a main method, which serves as the entry point for the Java program.
  • Inside the main method, a LinkedList object named col_list is created with a type parameter of String, indicating that it will store strings as its elements.
  • Strings such as "Green", "Blue", "Orange", "Black", "White", and "Pink" are added to col_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 initial contents of col_list before any modifications.
  • The col_list.pop() method is called to remove and return the first element in col_list. The pop method removes the first element from the linked list and returns its value, or throws a NoSuchElementException if the list is empty.
  • The value of the removed element is printed in a message "Removed Element : " followed by the value of col_list.pop().
  • Another System.out.println statement is used to print the contents of col_list after the pop operation, which will be the remaining elements in the linked list after the first element is removed.
  • The output of the program will be the initial contents of col_list printed on the first line, followed by the message "Removed Element : " printed on the second line with the value of the removed element, and the contents of col_list printed on the third line.

Source Code

import java.util.*;
public class Remove_Return
{
	public static void main(String[] args)
	{
		LinkedList <String> col_list = new LinkedList <String> ();
		col_list.add("Green");
		col_list.add("Blue");
		col_list.add("Orange");
		col_list.add("Black");
		col_list.add("White");
		col_list.add("Pink");
		System.out.println("Given linked  list: " + col_list);
		System.out.println("Removed Element : "+col_list.pop());
		System.out.println("Linked list After Pop Operation : "+col_list);
	}
}

Output

Given linked  list: [Green, Blue, Orange, Black, White, Pink]
Removed Element : Green
Linked list After Pop Operation : [Blue, Orange, Black, White, Pink]

Example Programs