LinkedList Basic Operations in Java
Problem
LinkedList stores its elements as a chain of linked nodes rather than a backing array, trading ArrayList's fast indexed access for fast insertion and removal at the ends.
Build a LinkedList of colors, read one by index, and remove another by value.
Java Program
import java.util.LinkedList;
public class LinkedListOperations {
public static void main(String[] args) {
LinkedList<String> colors = new LinkedList<>();
colors.add("Red");
colors.add("Green");
colors.add("Blue");
System.out.println("Element at index 1: " + colors.get(1)); // walks the chain to reach index 1
colors.remove("Green");
System.out.println("List: " + colors);
}
}Output
Core Logic
Adding three colors builds the chain in order, get(index) walks that chain to the requested position, and remove(value) unlinks the matching node.
- 1
add("Red"),add("Green"),add("Blue")each append a new node onto the end of the linked chain. - 2
get(1)starts from whichever end of the chain is closer to index 1 and walks node-by-node to reach it, returning"Green". - 3
remove("Green")searches for the first node holding that value and unlinks it, reconnecting its neighbors directly to each other. - 4The list that remains,
[Red, Blue], reflects that unlinking — no shifting of array slots is involved, since there's no backing array at all.
"Green", the two remaining nodes — Red and Blue — are linked directly to each other.Key Point: Unlike ArrayList's get(index), which jumps straight to a memory offset, LinkedList's get(index) has to walk the chain one node at a time — a real trade-off for the fast add/remove at either end that LinkedList is chosen for.
Why: get(index) must traverse up to n nodes from whichever end is nearer, unlike ArrayList's direct O(1) array access; add() at the end and remove() of an already-found node are both O(1) once the target node is reached.