Java ProgramsCollectionsLinkedList Remove First/Last

LinkedList Remove First/Last in Java

beginner·  Collections  ·  List

Problem

Because a LinkedList tracks its head and tail directly, removing from either end just detaches that one node and updates the reference, without touching the rest of the list.

Given a LinkedList of four elements, remove one from the front and one from the back, and print what remains.

Input
[A, B, C, D] — removeFirst(), removeLast()
Output
[B, C]

Java Program

Java
import java.util.LinkedList; public class LinkedListRemoveFirstLast { public static void main(String[] args) { LinkedList<String> list = new LinkedList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); list.removeFirst(); // detaches the current head list.removeLast(); // detaches the current tail System.out.println(list); } }

Output

[B, C]

Core Logic

removeFirst() and removeLast() each detach the head or tail node directly and update the list's reference to the next node in, leaving everything else untouched.

How It Works
  1. 1list.removeFirst() detaches "A", the current head, and makes "B" the new head.
  2. 2list.removeLast() detaches "D", the current tail, and makes "C" the new tail.
  3. 3Neither call touches the nodes in between — "B" and "C" are relinked only at the ends, not shifted or copied.
  4. 4The list that remains, [B, C], keeps its original relative order.
Starting from [A, B, C, D], removing the first element leaves [B, C, D], and then removing the last element leaves [B, C].
💡

Key Point: Both methods throw NoSuchElementException if the list is empty — the safer pollFirst()/pollLast() return null instead, which is often the better choice when an empty list is a normal, expected case rather than a bug.

Complexity
Time Complexity: O(1)Space Complexity: O(1)

Why: Removing the head or tail node just updates a single reference, with no dependency on how many elements remain in the list.

Key Concepts

LinkedListremoveFirst()removeLast()

Related Programs