Remove First and Last Elements of Linkedlist in Java



Java LinkedList Examples


In this post, we will learn how to remove the first and last element from LinkedList using the following APIs:
  • removeFirst()
  • removeLast()
Let's first create LinkedList with few fruits and then use remove methods to remove fruits from LinkedList.
LinkedList<String> fruitList = new LinkedList<>();

fruitList.add("Apple");
fruitList.add("banana");
fruitList.add("mango");
fruitList.add("Pinaple");

System.out.println("Initial LinkedList = " + fruitList);

removeFirst()

Remove the first element in the LinkedList. Throws NoSuchElementException if the LinkedList is empty.
String element = fruitList.removeFirst();   
System.out.println("Removed the first element " + element + " => " + fruitList);

removeLast()

Remove the last element in the LinkedList. Throws NoSuchElementException if the LinkedList is empty
element = fruitList.removeLast();    
System.out.println("Removed the last element " + element + " => " + fruitList);

Complete Example

package com.javaguides.collections.linkedlistexamples;

import java.util.LinkedList;

public class RemoveElementsFromLinkedListExample {
    public static void main(String[] args) {
        LinkedList < String > fruitList = new LinkedList < > ();

        fruitList.add("Apple");
        fruitList.add("banana");
        fruitList.add("mango");
        fruitList.add("Pinaple");

        System.out.println("Initial LinkedList = " + fruitList);

        // Remove the first element in the LinkedList
        String element = fruitList.removeFirst();
        System.out.println("Removed the first element " + element + " => " + fruitList);

        // Remove the last element in the LinkedList
        element = fruitList.removeLast();
        System.out.println("Removed the last element " + element + " => " + fruitList);
    }
}

Output

Initial LinkedList = [Apple, banana, mango, Pinaple]
Removed the first element Apple => [banana, mango, Pinaple]
Removed the last element Pinaple => [banana, mango]

Comments