A linked list stores each element in its own node: { value, next }. The nodes can live anywhere in memory; chains of next pointers give the order, and a head pointer marks the entry point. A doubly linked list adds a prev pointer for backward walks, and a tail pointer makes appends O(1).
This design trades away arrays' superpower and gains its own. Random access arr[i] is gone, reaching element 7 means walking 7 hops (O(n)). But inserting or deleting at a KNOWN position costs O(1): rewire two pointers and nothing shifts. The array had to move everything after the edit point; the list just re-plugs a link. That's the fundamental trade: arrays are fast to read by position, lists are fast to restructure.
Linked list vs array
| Operation / case | Cost | Notes |
|---|---|---|
| Access by index | O(n) | array: O(1), the big loss |
| Insert/delete at known node | O(1) | array: O(n), the big win |
| Insert at front | O(1) | array: O(n) (shift) |
| Search by value | O(n) | same as unsorted array |
| Memory | per-node overhead | extra pointer(s) + allocation per node; poor CPU cache locality |
Implementation: singly linked list
class ListNode {
constructor(value, next = null) {
this.value = value;
this.next = next;
}
}
class LinkedList {
constructor() { this.head = null; this.size = 0; }
// Insert at front, O(1)
prepend(value) {
this.head = new ListNode(value, this.head);
this.size++;
}
// Insert at end, O(n) without a tail pointer
append(value) {
const node = new ListNode(value);
if (!this.head) { this.head = node; }
else {
let cur = this.head;
while (cur.next) cur = cur.next; // walk to the last node
cur.next = node;
}
this.size++;
}
// Delete first node with value, O(n) search + O(1) rewire
remove(value) {
if (!this.head) return false;
if (this.head.value === value) { this.head = this.head.next; this.size--; return true; }
let cur = this.head;
while (cur.next && cur.next.value !== value) cur = cur.next;
if (cur.next) { cur.next = cur.next.next; this.size--; return true; } // the rewire
return false;
}
toArray() {
const out = [];
for (let cur = this.head; cur; cur = cur.next) out.push(cur.value);
return out;
}
}The fast/slow idiom (Floyd's cycle detection)
// Does the list contain a cycle? Two pointers, different speeds.
function hasCycle(head) {
let slow = head, fast = head;
while (fast && fast.next) {
slow = slow.next; // 1 hop
fast = fast.next.next; // 2 hops
if (slow === fast) return true; // they can only meet inside a loop
}
return false; // fast hit the end → no cycle
}
// O(n) time, O(1) space. Finding the middle works the same way:
// when fast reaches the end, slow is at the midpoint.