Why linked lists exist
26 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)An array stores all elements side by side in one memory block. Index lookup arr[i] is O(1), but front insertion shifts up to n items. A linked list stores each value in a node object pointing to the next node.
Arrays versus nodes in memory
A linked list is a chain of nodes where each node holds a value and a reference to the next node. Adding or removing at a known node is O(1), but reaching the i-th node is O(n).
A singly linked list stores items in separate objects called nodes, while an array keeps them in one block of memory. Each node holds val (the value) and next (a reference to the next node). The last node has next == null.
class Node { int val; // the value Node next; // the next node, or null at the end Node(int val, Node next) { this.val = val; this.next = next; }}int[] arr = {10, 20, 30}; // one block of 3 slotsNode head = new Node(10, new Node(20, new Node(30, null))); // 3 separate node objectsWhen you run new int[5], Java reserves one block of 5 slots in memory. From the start address, the CPU finds arr[i] in one step (O(1) time). When an ArrayList fills up, it must allocate a bigger array and copy all n items. Inserting at index 0 also shifts every item one slot right in O(n) time.
The list only needs a reference to the first node, called head. When the list is empty, head is null. Inserting or removing a node at a known spot only rewires one or two next links.
- Contiguous array: instant
arr[i]lookup in O(1), but front or middle shifts take O(n). - Linked nodes: no shifting on insert, but reaching index
iwalksisteps fromhead. - Memory use: each
Nodeobject has header and pointer fields, so it uses more memory thanint[].
A Node class with next
For pointer problems, we write a small static class Node with int val and Node next fields. A one-arg constructor Node(int val) leaves next = null, while Node(int val, Node next) wires both fields at once.
- Create three nodes:
Node a = new Node(10); Node b = new Node(20); Node c = new Node(30);. - Link
atob:a.next = b;(10 -> 20 -> null). - Link
btoc:b.next = c;(10 -> 20 -> 30 -> null). - Or chain the two-argument constructor:
Node head = new Node(10, new Node(20, new Node(30, null)));.
Example 1 · Creating and Wiring Nodes by Hand
public class ManualNodeWiring { static class Node { int val; Node next;
Node(int val) { this.val = val; }
Node(int val, Node next) { this.val = val; this.next = next; } }
public static void main(String[] args) { Node first = new Node(10); Node second = new Node(20); Node third = new Node(30);
first.next = second; second.next = third;
System.out.println("first.val = " + first.val); System.out.println("first.next.val = " + first.next.val); System.out.println("first.next.next.val = " + first.next.next.val); System.out.println("first.next.next.next = " + first.next.next.next); }}first.val = 10 first.next.val = 20 first.next.next.val = 30 first.next.next.next = null
What this code does
first.nextpoints tosecond, andfirst.next.nextpoints tothird.- Because
third.nextwas never set, it staysnulland marks the end of the list.
The three nodes now form the chain 10 -> 20 -> 30 -> null, and first is the only variable the rest of the program needs.
Predict the output
Follow the next links
Read the code and pick what it prints.
Round 1 of 2
a.next = b does not copy object b. Both b and a.next point to the same Node(20) object.Cost of insert and access, and Java's LinkedList versus your own
Inserting into a linked list is O(1) only when you hold the node before the spot. Without that reference, walking to index i - 1 from head takes O(i) time.
Example 2 · Splicing a New Node in O(1) When You Hold the Predecessor Reference
public class SpliceInO1Demo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static void printChain(Node head) { StringBuilder sb = new StringBuilder(); for (Node curr = head; curr != null; curr = curr.next) { sb.append(curr.val).append(" -> "); } sb.append("null"); System.out.println(sb); }
public static void main(String[] args) { Node third = new Node(30, null); Node first = new Node(10, third); printChain(first);
// Insert 20 right after 'first' in O(1) pointer updates: Node inserted = new Node(20, first.next); first.next = inserted; printChain(first);
// Bypass (delete) 20 in O(1) using 'first': first.next = first.next.next; printChain(first); }}10 -> 30 -> null 10 -> 20 -> 30 -> null 10 -> 30 -> null
What this code does
- Set
inserted.next = first.nextbeforefirst.next = insertedso you do not loseNode(30). - To delete the node after
first,first.next = first.next.nextskips20in O(1) time.
Example 3 · Comparing Cost of get(i) vs addFirst(x): Array vs Linked Nodes
import java.util.LinkedList;
public class ArrayVsLinkedCostDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
static int getAtIndex(Node head, int index) { Node curr = head; int steps = 0; while (curr != null && steps < index) { curr = curr.next; steps++; } if (curr == null) throw new IndexOutOfBoundsException("Index: " + index); return curr.val; }
public static void main(String[] args) { Node head = null; for (int x = 50; x >= 10; x -= 10) { head = new Node(x, head); // O(1) prepend at head } System.out.println("Custom list index 0: " + getAtIndex(head, 0)); System.out.println("Custom list index 3: " + getAtIndex(head, 3));
LinkedList<Integer> jdkList = new LinkedList<>(); jdkList.addFirst(20); jdkList.addFirst(10); jdkList.addLast(30); System.out.println("java.util.LinkedList: " + jdkList); }}Custom list index 0: 10 Custom list index 3: 40 java.util.LinkedList: [10, 20, 30]
What this code does
- Prepending 5 items with
head = new Node(x, head)takes O(1) time per item. getAtIndex(head, 3)walkscurr = curr.next3 times, whereasarr[3]takes 1 step.
Where a linked list is fast:
- Insert or delete at
head: O(1) time withhead = new Node(x, head);. - Insert or delete after a known node
curr: O(1) time withnewNode.next = curr.next; curr.next = newNode;.
In Stage 1 you used java.util.LinkedList<E>, which is a doubly linked list. For everyday lists and queues, ArrayList and ArrayDeque are faster because arrays sit together in CPU cache. You build your own Node class when:
- Solving pointer problems or custom structures: reversing in O(1) space, finding cycles, or building an LRU Cache.
Next step
Check your understanding
10 quick questions