๐ 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