Write a Java program to Retrieve and Remove the head item from the LinkedList


The code demonstrates how to use the poll method of LinkedList in Java to retrieve and remove the item at the head (beginning) of the list.

In the Retrieve_RemoveHead class, a LinkedList object named list is created without specifying a type parameter, allowing it to hold items of any type. Several items of different types, including 18, "JAVA", 54.78, 'J', and true, are added to the list using the add method.

The System.out.println statements are used to print the items in the list before and after calling the poll method. The poll method retrieves and removes the item at the head (beginning) of the list, and returns null if the list is empty. In this example, the head item is printed using the poll method twice, and the updated list is printed after each call.

Note that poll removes the item from the list, so the list is modified after calling poll. If you want to retrieve the head item without removing it, you can use the peek method instead. Also, keep in mind that poll has a time complexity of O(1) as it operates on the head of the list.

Source Code

import java.util.LinkedList;
public class Retrieve_RemoveHead
{
	public static void main(String[] args) 
	{
		LinkedList list = new LinkedList();
		list.add(18);
		list.add("JAVA");
		list.add(54.78);
		list.add('J');
		list.add(true);
 
		System.out.println("LinkedList Items : " + list);
		System.out.println("Head Item : " + list.poll());
		System.out.println("LinkedList Items : " + list);
		System.out.println("Head Item : " + list.poll());
		System.out.println("LinkedList Items : " + list);
	}
}

Output

LinkedList Items : [18, JAVA, 54.78, J, true]
Head Item : 18
LinkedList Items : [JAVA, 54.78, J, true]
Head Item : JAVA
LinkedList Items : [54.78, J, true]

Example Programs