LinkedList Add First/Last in Java
beginner· Collections · List
Problem
A LinkedList keeps direct references to both its head and tail nodes, so it can insert at either end without shifting any other element.
Given a LinkedList, insert elements at both its front and back, and print the result in order.
Input
addLast(B), addLast(C), addFirst(A), addLast(D)
Output
[A, B, C, D]
Java Program
Java
import java.util.LinkedList;
public class LinkedListAddFirstLast {
public static void main(String[] args) {
LinkedList<String> list = new LinkedList<>();
list.addLast("B");
list.addLast("C");
list.addFirst("A"); // attaches directly before the current head
list.addLast("D");
System.out.println(list);
}
}Output
[A, B, C, D]
Core Logic
addFirst() and addLast() each attach a new node directly to the list's head or tail reference, without needing to touch any node in between.
How It Works
- 1
list.addLast("B")andlist.addLast("C")build up the middle and end of the list first, in order. - 2
list.addFirst("A")then attaches a new node directly before the current head, becoming the new first element. - 3
list.addLast("D")attaches one more node directly after the current tail, becoming the new last element. - 4The final order —
[A, B, C, D]— reflects each insertion's position, not the order the calls were made in.
Starting from an empty list, the calls in this order build up
[B], then [B, C], then [A, B, C], then [A, B, C, D].💡
Key Point: An ArrayList could do the same thing with add(0, value) for the front, but that shifts every existing element over by one position — a LinkedList's addFirst() never has to move anything else at all.
Complexity
Time Complexity: O(1)Space Complexity: O(1)
Why: Both addFirst() and addLast() just attach a new node to an existing head or tail reference, with no dependency on how many elements the list already holds.
Key Concepts
LinkedListaddFirst()addLast()