π Linked List
One-line summary: A dynamic chain of nodes β O(1) insert/delete at known position, O(n) access by index. Master reversal, cycle detection, and merge patterns.
Conceptβ
Each node: val + next pointer (singly), or prev+next (doubly).
Types: Singly, Doubly, Circular.
Diagramβ
Time & Space Complexityβ
| Operation | Time | Space |
|---|---|---|
| Access by index | O(n) | O(1) |
| Insert/Delete at head | O(1) | O(1) |
| Reverse | O(n) | O(1) |
| Cycle detection (Floyd's) | O(n) | O(1) |
| Find middle | O(n) | O(1) |
Common Patternsβ
Reverse (Iterative)β
function reverseList(head) {
let prev = null, curr = head;
while (curr) { const next = curr.next; curr.next = prev; prev = curr; curr = next; }
return prev;
}
Cycle Detection (Floyd's)β
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next; fast = fast.next.next;
if (slow === fast) return true;
}
return false;
}
Find Middleβ
function findMiddle(head) {
let slow = head, fast = head;
while (fast && fast.next) { slow = slow.next; fast = fast.next.next; }
return slow;
}
Merge Two Sorted Listsβ
function mergeTwoLists(l1, l2) {
const dummy = { next: null }; let cur = dummy;
while (l1 && l2) {
if (l1.val <= l2.val) { cur.next = l1; l1 = l1.next; }
else { cur.next = l2; l2 = l2.next; }
cur = cur.next;
}
cur.next = l1 || l2;
return dummy.next;
}
Pitfallsβ
- Losing reference to
nextbefore reassigning β store it first - Forgetting to update
tail.next = nullafter reversal - Off-by-one in middle finding: even-length list has two middles
Practice Problemsβ
Related Topicsβ
- Two Pointers β fast/slow is a linked-list technique
- Stack β LRU = doubly linked list + hash map
- Trees β tree nodes are linked nodes with more pointers
β Back to Home Β· Β© sparshjaswal