Java ProgramsCollectionsLinkedList Basic Operations

LinkedList Basic Operations in Java

beginner·  Collections  ·  List

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.

Input
add("Red"), add("Green"), add("Blue")
Output
Element at index 1: Green

Java Program

Java
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

Element at index 1: Green List: [Red, Blue]

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.

How It Works
  1. 1add("Red"), add("Green"), add("Blue") each append a new node onto the end of the linked chain.
  2. 2get(1) starts from whichever end of the chain is closer to index 1 and walks node-by-node to reach it, returning "Green".
  3. 3remove("Green") searches for the first node holding that value and unlinks it, reconnecting its neighbors directly to each other.
  4. 4The list that remains, [Red, Blue], reflects that unlinking — no shifting of array slots is involved, since there's no backing array at all.
After removing "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.

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

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.

Key Concepts

LinkedListadd()get()remove()

Related Programs