1. Home
  2. Explore
  3. Computer Science
  4. Linked Lists Introduction

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

Linked Lists Introduction

Linked Lists: Comprehensive Study Notes

What is a Linked List?

A linked list is a linear data structure made up of a sequence of nodes. Each node contains two components:

  • Data (any type: string, number, boolean, object, etc.)

  • A pointer (or reference) to the next node in the sequence

This pointer is often called next. The last node's next pointer points to null (or nil), indicating the end of the list.

Key Terminology

  • Head: The very first node in a linked list.

  • Tail: The very last node in a linked list (its next is null).

  • A linked list is an ordered data structure – nodes are arranged sequentially by following next pointers from the head to the tail.

A linked list is a collection of nodes linked together via pointers. Its order is inherent: starting at the head and following next leads through all nodes in sequence.

Visual Representation

Nodes are often drawn as circles with data inside, and arrows representing next pointers:

[ A ] → [ B ] → [ C ] → [ D ] → null
head                             tail

Linked List vs. Array: Key Differences

Both arrays and linked lists store ordered data, but they differ fundamentally in memory layout and operation costs.

Feature

Array

Linked List

Memory Layout

Contiguous – elements stored next to each other in memory

Non-contiguous – nodes can be anywhere in memory; linked via pointers

Insertion in Middle

O(n)O(n)O(n) – must shift all elements after the insertion point

O(1)O(1)O(1) – only need to adjust two pointers (prev node's next and new node's next)

Access by Index

O(1)O(1)O(1) – direct indexed access

O(n)O(n)O(n) – must traverse from head to the desired index

Space Overhead

Minimal (only data)

Extra space per node for the next pointer

Example: Inserting 'Q' at index 2

Array approach:

  1. Shift elements C and D to the right.

  2. Insert Q at index 2.

    • Requires moving O(n)O(n)O(n) elements in worst case (if inserting at the beginning).

Linked list approach:

  1. Create new node Q.

  2. Point B's next to Q.

  3. Point Q's next to C.

    • Constant O(1)O(1)O(1) operations regardless of list length.


Core Linked List Traversal

Traversal – visiting every node of a linked list – is the foundation of almost all linked list algorithms. The function receives only the head node; from it, the entire list is accessible.

Iterative Traversal

const printLinkedList = (head) => {
  let current = head;
  while (current !== null) {
    console.log(current.val);
    current = current.next;
  }
};

Key pattern: Use a current pointer, loop while current !== null, process the node, then advance current = current.next.

  • Always write conditions about the current node, not current.next (otherwise the last node gets skipped).

  • The loop ends when current becomes null.

Recursive Traversal

const printLinkedList = (head) => {
  if (head === null) return;
  console.log(head.val);
  printLinkedList(head.next);
};

Base case: head === null – the empty list or end of list.
Recursive case: Process the current node, then call recursively on head.next.

  • Each recursive call corresponds to a node; total calls = number of nodes.

Complexity

  • Time: O(n)O(n)O(n) (visit each node once)

  • Space:

    • Iterative: O(1)O(1)O(1) (only a few variables)

    • Recursive: O(n)O(n)O(n) (call stack grows with list length)


Problem: Linked List Values

Goal: Given the head of a singly linked list, return an array containing all node values in order.

Iterative Solution

const linkedListValues = (head) => {
  const values = [];
  let current = head;
  while (current !== null) {
    values.push(current.val);
    current = current.next;
  }
  return values;
};
  • Initialize empty array.

  • Traverse list, pushing each node's value.

  • Return array after loop.

Recursive Solution (using a helper)

const linkedListValues = (head) => {
  const values = [];
  fillValues(head, values);
  return values;
};

const fillValues = (head, values) => {
  if (head === null) return;
  values.push(head.val);
  fillValues(head.next, values);
};
  • Use a helper that mutates the same array (passed by reference). This avoids creating multiple arrays and keeps space O(n)O(n)O(n) only for the call stack.

Complexity: Time O(n)O(n)O(n), Space O(n)O(n)O(n) (output array) + O(n)O(n)O(n) recursion stack.


Problem: Sum List

Goal: Given the head of a linked list containing numbers, return the total sum of all values.

Iterative Solution

const sumList = (head) => {
  let sum = 0;
  let current = head;
  while (current !== null) {
    sum += current.val;
    current = current.next;
  }
  return sum;
};
  • Initialize sum = 0.

  • Traverse, adding each node's value.

  • Return sum.

Recursive Solution

const sumList = (head) => {
  if (head === null) return 0;
  return head.val + sumList(head.next);
};
  • Base case: Empty list (or past end) → return 0.

  • Recursive case: Add current node's value to the sum of the rest of the list.

  • Call stack builds; each frame holds a pending addition.

Complexity: Time O(n)O(n)O(n), Space O(1)O(1)O(1) (iterative) vs O(n)O(n)O(n) (recursive stack).


Problem: Linked List Find

Goal: Given a linked list head and a target value, return true if the target exists in the list, otherwise false.

Iterative Solution

const linkedListFind = (head, target) => {
  let current = head;
  while (current !== null) {
    if (current.val === target) return true;
    current = current.next;
  }
  return false;
};
  • Traverse; if current value matches target, return true immediately.

  • If loop finishes without finding, return false.

Common mistake: Placing the return false inside the loop (e.g., else return false). The false return must come only after all nodes have been checked.

Recursive Solution

const linkedListFind = (head, target) => {
  if (head === null) return false;
  if (head.val === target) return true;
  return linkedListFind(head.next, target);
};
  • Two base cases:

    1. head === null → target not found, return false.

    2. head.val === target → found, return true.

  • Recurse on the rest.

Complexity: Time O(n)O(n)O(n), Space O(1)O(1)O(1) (iterative) vs O(n)O(n)O(n) (recursive).


Problem: Get Node Value

Goal: Given a linked list head and an index (0-based), return the value of the node at that index. If index is out of bounds, return null.

Iterative Solution

const getNodeValue = (head, index) => {
  let current = head;
  let count = 0;
  while (current !== null) {
    if (count === index) return current.val;
    count++;
    current = current.next;
  }
  return null;
};
  • Count upward from 0.

  • When count equals target index, return current value.

  • If loop exits, index was too large; return null.

Recursive Solution (count downward)

const getNodeValue = (head, index) => {
  if (head === null) return null;
  if (index === 0) return head.val;
  return getNodeValue(head.next, index - 1);
};
  • Base case 1: head === null → index out of range, return null.

  • Base case 2: index === 0 → current node is the one, return its value.

  • Recursive case: Decrement index and recurse on head.next.

Complexity: Time O(n)O(n)O(n), Space O(1)O(1)O(1) (iterative) vs O(n)O(n)O(n) (recursive stack).


Problem: Reverse List

Goal: Reverse a singly linked list in place (mutating the existing nodes). Return the new head of the reversed list.

Iterative Solution

const reverseList = (head) => {
  let prev = null;
  let current = head;
  while (current !== null) {
    const next = current.next;   // save next before overwriting
    current.next = prev;         // reverse pointer
    prev = current;              // move prev forward
    current = next;              // move current forward
  }
  return prev;                   // new head (old tail)
};

Key steps per iteration:

  1. Save next (the original next node).

  2. Set current.next = prev (reverse the arrow).

  3. Move prev to current.

  4. Move current to next.

    • When loop ends, current is null and prev points to the new head (original tail).

Recursive Solution

const reverseList = (head, prev = null) => {
  if (head === null) return prev;
  const next = head.next;
  head.next = prev;
  return reverseList(next, head);
};
  • Base case: head === null → return prev (new head).

  • Recursive case: Save next, reverse pointer, recurse with next as new head and head as new prev.

  • This recursively reverses the list. The function returns the new head all the way up.

Complexity: Time O(n)O(n)O(n), Space O(1)O(1)O(1) (iterative) vs O(n)O(n)O(n) (recursive stack).


Problem: Zipper List (or Merge Alternating)

Goal: Given two linked lists, zipper them together in place by alternating nodes, starting with the first node of list one. If one list runs out, append the remaining nodes of the other list. Return the head of the zippered list (which is the head of list one).

Iterative Solution

const zipperLists = (head1, head2) => {
  let tail = head1;
  let current1 = head1.next;
  let current2 = head2;
  let count = 0;

  while (current1 !== null && current2 !== null) {
    if (count % 2 === 0) {
      tail.next = current2;
      current2 = current2.next;
    } else {
      tail.next = current1;
      current1 = current1.next;
    }
    tail = tail.next;
    count++;
  }

  // Attach remaining nodes
  if (current1 !== null) tail.next = current1;
  if (current2 !== null) tail.next = current2;

  return head1;
};

Key points:

  • Start with tail = head1 (first node always from list one).

  • Use a counter to decide which list to take the next node from: even → list two, odd → list one.

  • Advance the appropriate pointer and always update tail.

  • After the loop (when one list is exhausted), attach the remainder of the other list.

  • The function returns head1 (original head of first list), which becomes the head of the zippered list.

Recursive Solution

const zipperLists = (head1, head2) => {
  if (head1 === null && head2 === null) return null;
  if (head1 === null) return head2;
  if (head2 === null) return head1;

  const next1 = head1.next;
  const next2 = head2.next;

  head1.next = head2;               // link head1 to head2
  head2.next = zipperLists(next1, next2); // recursively zipper the rest

  return head1;
};
  • Base cases: If both null → return null; if only one null → return the other (it's the remainder).

  • Recursive logic: Link head1.next to head2, then recursively zipper the remaining tails (next1 and next2). The result of recursion becomes head2.next.

  • This builds the zippered list from the front backwards.

Complexity: Time O(min⁡(n,m))O(\min(n, m))O(min(n,m)) (only iterate until the shorter list ends, then attach the rest in O(1)O(1)O(1)). Space O(1)O(1)O(1) (iterative) vs O(min⁡(n,m))O(\min(n, m))O(min(n,m)) recursion stack.


Summary of Core Patterns

  1. Traversal: while (current !== null) { ... current = current.next; }

  2. Stay present: Always write conditions and expressions about the current node, not current.next.

  3. Save pointers before overwriting: Especially in reverse and zipper problems.

  4. Recursive thinking: Base case usually involves null (empty list). Recurse on head.next.

  5. Complexity: Most linked list operations are O(n)O(n)O(n) time; iterative solutions are O(1)O(1)O(1) space, recursive solutions are O(n)O(n)O(n) space due to call stack.

Master these patterns, and you will be well-prepared for linked list problems in coding interviews and real-world projects.

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent