Linked Lists

Nodes connected by pointers — O(1) insertion anywhere you already are, at the price of O(n) access.

Beginner 3 min readLesson 3 of 16 Interview Q&A

A linked list stores elements in separate nodes, each holding a value and a pointer (reference) to the next node. Nodes can live anywhere in memory — the pointers stitch them into a sequence.

head3819null
Singly linked list: each node points to the next; the last points to null.

Arrays vs linked lists

Array
  • Contiguous memory
  • O(1) access by index
  • O(n) insert/delete in middle (shifting)
  • Excellent cache locality
  • Fixed size or amortized resizing
Linked list
  • Scattered nodes + pointers
  • O(n) access by index (must walk)
  • O(1) insert/delete given the node
  • Poor cache locality (pointer chasing)
  • Grows one node at a time; extra memory per node for pointers

Variants

  • Singly linked — next only. Minimal memory; can only move forward.
  • Doubly linked — prev and next. O(1) removal of a known node and backward traversal. Java's LinkedList, the LRU cache.
  • Circular — the tail points back to the head. Round-robin schedulers, ring buffers.
headABCnull
Doubly linked list: each node points both ways.

Implementation

class ListNode {
    int val;
    ListNode next;
    ListNode(int val) { this.val = val; }
}

class LinkedList {
    private ListNode head;
    private int size;

    void addFirst(int val) {            // O(1)
        ListNode n = new ListNode(val);
        n.next = head;
        head = n;
        size++;
    }

    void addLast(int val) {             // O(n) without a tail pointer
        ListNode n = new ListNode(val);
        if (head == null) { head = n; size++; return; }
        ListNode cur = head;
        while (cur.next != null) cur = cur.next;
        cur.next = n;
        size++;
    }

    boolean remove(int val) {           // O(n): find, then unlink
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        for (ListNode prev = dummy; prev.next != null; prev = prev.next) {
            if (prev.next.val == val) {
                prev.next = prev.next.next;   // unlink
                head = dummy.next;
                size--;
                return true;
            }
        }
        return false;
    }
}

Complexity

OperationSinglyDoubly (with tail)
Access i-thO(n)O(n)
Insert at headO(1)O(1)
Insert at tailO(n) / O(1) with tailO(1)
Delete given nodeO(n) (need prev)O(1)
SearchO(n)O(n)

Classic techniques

InteractiveReverse a linked list in place
1
→ 2
curr
2
→ 3
3
→ 4
4
→ 5
5
→ null
prevcurr
prev = null, curr = head
1/12
Key takeaways
  • Linked lists trade O(1) indexing for O(1) splicing at a known node.
  • Doubly linked lists allow O(1) deletion of a known node — the basis of LRU caches.
  • Use a dummy head to eliminate edge cases; draw the pointers before coding.
  • In practice arrays usually win because of cache locality.
Interview questions
QDetect whether a linked list has a cycle.easy

Floyd's tortoise and hare: slow moves 1 step, fast moves 2. If they ever meet there's a cycle; if fast reaches null there isn't. O(n) time, O(1) space. To find the cycle start, reset one pointer to head and move both 1 step until they meet.

QFind the middle node in one pass.easy

Fast/slow pointers again: when fast reaches the end, slow is at the middle.

QRemove the n-th node from the end in one pass.medium

Advance fast n steps, then move fast and slow together until fast.next is null; slow.next is the node to delete. Start both at a dummy node so deleting the head works.

QHow would you delete a node when you're only given that node (not the head)?medium

Copy the next node's value into it and unlink the next node: node.val = node.next.val; node.next = node.next.next. Doesn't work for the tail.