See how nodes connect in memory, add and remove them live, and understand what references really are.
Nodes are scattered across memory — not stored contiguously like arrays. Each node holds the address of the next.
A variable doesn't contain an object. It contains a memory address — a pointer to where the object actually lives in heap memory.
When you write head.next = new Node(3), you're saying: "store the address of the new Node object inside head.next."
This is why linked lists work — each node stores the address of the next node, not the node itself. The nodes can live anywhere in memory.
// Node definition class Node { int val; Node next; Node(int val) { this.val = val; this.next = null; } } // Usage Node head = new Node(5); head.next = new Node(12); head.next.next = new Node(8); // Traversal Node curr = head; while (curr != null) { System.out.println(curr.val); curr = curr.next; }
| Operation | Array | Linked List |
|---|---|---|
| Access by index | O(1) | O(n) |
| Insert at head | O(n) | O(1) |
| Delete at head | O(n) | O(1) |
| Insert at end | O(1)* | O(n) |
| Search | O(n) | O(n) |
| Memory | Contiguous | Scattered |
* Amortized O(1) for dynamic arrays