Write a Java program to Retrieve and Remove the tail/last item from the LinkedList


The code demonstrates how to use the pollLast method of LinkedList in Java to retrieve and remove the item at the tail (end) of the list. In the Retrieve_Remove 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 pollLast method. The pollLast method retrieves and removes the item at the tail (end) of the list, and returns null if the list is empty. In this example, the tail item is printed using pollLast method twice, and the updated list is printed after each call.

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

Source Code

import java.util.LinkedList;
public class Retrieve_Remove
{
	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("Tail Item : " + list.pollLast());
		System.out.println("LinkedList Items : " + list);
		System.out.println("Tail Item : " + list.pollLast());
		System.out.println("LinkedList Items : " + list);
	}
}

Output

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

Example Programs