LinkedList Remove First/Last in Java
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.
Java Program
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
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.
- 1
list.removeFirst()detaches"A", the current head, and makes"B"the new head. - 2
list.removeLast()detaches"D", the current tail, and makes"C"the new tail. - 3Neither call touches the nodes in between —
"B"and"C"are relinked only at the ends, not shifted or copied. - 4The list that remains,
[B, C], keeps its original relative order.
[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.
Why: Removing the head or tail node just updates a single reference, with no dependency on how many elements remain in the list.