โ Back
Data StructureBeginner
๐
Linked List
Connected nodes forming a chain
โฑ๏ธ 4โ6 hours๐งฉ 10 LeetCode
โจ Create a free account to track your progress and unlock solutions.
What is it?
A linked list is like a treasure hunt. Each clue (node) tells you the value and where the next clue is.
- Each node stores a value and a pointer to the next node.
- Unlike arrays, nodes live anywhere in memory โ not side by side.
- Inserting at the front is O(1), but finding item #5 takes O(n) steps.
Variants / Subtypes
- Singly Linked List โ each node points forward only
- Doubly Linked List โ each node points both forward and backward
- Circular Linked List โ last node points back to the head
Real-World Examples
Music playlist (next song)
Browser back/forward
Train compartments
Undo history in editors
OS free-memory list
Implementing stacks & queues
Code Example
What this code shows
Build three nodes holding 1, 2, 3 and chain them together (1 โ 2 โ 3). Then walk the chain from head to tail, printing each value along the way.
class Node {
constructor(val) {
this.val = val;
this.next = null; // pointer to next node
}
}
// create nodes and link them: 1 โ 2 โ 3
const a = new Node(1);
const b = new Node(2);
const c = new Node(3);
a.next = b;
b.next = c;
// traverse from head until null
let cur = a;
while (cur !== null) {
console.log(cur.val); // prints 1, then 2, then 3
cur = cur.next; // move to next node
}Expected Output
1 2 3