Skip to the content

Lesson 133 of 296

Linked lists

What you will learn

  • How linked lists differ from arrays
  • Traversing, inserting and deleting
  • The dummy head trick
  • Reverse Linked List
  • Merge Two Sorted Lists
  • Remove Nth Node From End
  • Reorder List
  • Doubly linked lists
On this page

Linked lists vs arrays

A singly linked list is a chain of nodes; each node points to the next (Lesson 124 defined ListNode). The list is known only by its head (first node).

OperationArrayLinked list
Read item iO(1)O(n): walk from the head
Insert or delete at the frontO(n): everything shiftsO(1)
Insert or delete after a known nodeO(n)O(1): change two references
MemoryOne blockSpread out; extra space for references

In JavaScript day to day you use arrays, but linked lists are very common in interviews because they test careful handling of references and null.

Traversing

TypeScript
function listLength(head: ListNode | null): number {
  let count = 0;
  let node = head;
  while (node !== null) {
    count++;
    node = node.next;
  }
  return count;
}

Always check for null before using .next. Draw boxes and arrows on paper; it prevents most bugs.

The dummy head trick

Operations that might change the head (delete the first node, merge lists) need special cases. A dummy (sentinel) node placed before the head removes them:

TypeScript
function removeValue(head: ListNode | null, val: number): ListNode | null {
  const dummy = new ListNode(0, head);
  let current = dummy;
  while (current.next !== null) {
    if (current.next.val === val) current.next = current.next.next;
    else current = current.next;
  }
  return dummy.next;
}

Return dummy.next, the real (possibly new) head.

Reverse Linked List

Problem (LeetCode 206): reverse the list. A very common question; practise until you can write it in one minute.

Iterative: walk through the list, turning each arrow around. Keep three references: previous, current, and next (saved before you overwrite the arrow).

TypeScript
function reverseList(head: ListNode | null): ListNode | null {
  let previous: ListNode | null = null;
  let current = head;
  while (current !== null) {
    const next = current.next;
    current.next = previous;
    previous = current;
    current = next;
  }
  return previous;
}
Start:  null   1 -> 2 -> 3 -> null
Step 1: null <- 1    2 -> 3 -> null
Step 2: null <- 1 <- 2    3 -> null
Step 3: null <- 1 <- 2 <- 3       previous is the new head

O(n) time, O(1) space.

Recursive: reverse the rest, then point the next node back at this one.

TypeScript
function reverseListRecursive(head: ListNode | null): ListNode | null {
  if (head === null || head.next === null) return head;
  const newHead = reverseListRecursive(head.next);
  head.next.next = head;
  head.next = null;
  return newHead;
}

O(n) time, O(n) stack space.

Merge Two Sorted Lists

Problem (LeetCode 21): merge two sorted lists into one sorted list.

Same idea as merging in merge sort (Lesson 121), with a dummy head:

TypeScript
function mergeTwoLists(a: ListNode | null, b: ListNode | null): ListNode | null {
  const dummy = new ListNode(0);
  let tail = dummy;
  while (a !== null && b !== null) {
    if (a.val <= b.val) {
      tail.next = a;
      a = a.next;
    } else {
      tail.next = b;
      b = b.next;
    }
    tail = tail.next;
  }
  tail.next = a ?? b;
  return dummy.next;
}

When one list runs out, attach the rest of the other (a ?? b). O(n + m) time, O(1) extra space (nodes are reused, not copied).

Remove Nth Node From End of List

Problem (LeetCode 19): remove the nth node from the end, in one pass.

Idea: move a fast pointer n steps ahead, then move fast and slow together. When fast reaches the last node, slow is just before the node to remove. The dummy handles removing the head.

TypeScript
function removeNthFromEnd(head: ListNode | null, n: number): ListNode | null {
  const dummy = new ListNode(0, head);
  let fast: ListNode | null = dummy;
  let slow: ListNode = dummy;
  for (let i = 0; i < n; i++) fast = fast!.next;
  while (fast!.next !== null) {
    fast = fast!.next;
    slow = slow.next!;
  }
  slow.next = slow.next!.next;
  return dummy.next;
}

O(n) time, O(1) space.

Reorder List

Problem (LeetCode 143): reorder L0 → L1 → ... → Ln into L0 → Ln → L1 → Ln-1 → ..., in place.
1 → 2 → 3 → 4 → 5 becomes 1 → 5 → 2 → 4 → 3.

Combines three techniques:

  1. Find the middle (fast and slow, Lesson 124).
  2. Reverse the second half.
  3. Merge the two halves by alternating nodes.
TypeScript
function reorderList(head: ListNode | null): void {
  if (head === null || head.next === null) return;

  let slow: ListNode = head;
  let fast: ListNode | null = head;
  while (fast !== null && fast.next !== null) {
    slow = slow.next!;
    fast = fast.next.next;
  }

  let second = reverseList(slow.next);
  slow.next = null;

  let first: ListNode | null = head;
  while (second !== null) {
    const nextFirst: ListNode | null = first!.next;
    const nextSecond: ListNode | null = second.next;
    first!.next = second;
    second.next = nextFirst;
    first = nextFirst;
    second = nextSecond;
  }
}

O(n) time, O(1) space. A great problem because it tests three skills at once.

Doubly linked lists

Each node also has a prev reference. This allows O(1) removal of a node when you have a reference to it, and moving in both directions. Used in the classic LRU cache design (Lesson 83).

Testing linked list code

Test with: an empty list (null), one node, two nodes, and an odd and even number of nodes. Write helpers to build a list from an array and convert back (Lesson 124's listFromArray and listToArray).

How to say it in an interview

"A linked list gives O(1) insertion and deletion at a known position but O(n) access by index. I always null-check before following next, draw the pointers, and use a dummy head so operations that change the head need no special cases. I reverse iteratively with previous, current and saved next. Merge uses a dummy and a tail pointer. Remove nth from end keeps a gap of n between two pointers. Reorder List combines finding the middle, reversing the second half and interleaving."

Key words

WordMeaning
Singly linked listNodes that point only to the next node
Head / tailThe first / last node
Dummy (sentinel) nodeA fake node before the head that simplifies code
Doubly linked listNodes that point to both next and previous

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.