Lesson 10 of 20

Linked List

Linked List

A Linked List is a sequence of nodes, where each node holds a value and a reference (pointer) to the next node. Unlike arrays, there is no contiguous memory — nodes can be anywhere in memory.

head → [1 | →] → [2 | →] → [3 | null]

Node Structure

class ListNode {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

Key Operations

class LinkedList {
  constructor() { this.head = null; }

  append(value) {
    const node = new ListNode(value);
    if (!this.head) { this.head = node; return; }
    let curr = this.head;
    while (curr.next) curr = curr.next;
    curr.next = node;
  }

  prepend(value) {
    const node = new ListNode(value);
    node.next = this.head;
    this.head = node;
  }

  delete(value) {
    if (!this.head) return;
    if (this.head.value === value) { this.head = this.head.next; return; }
    let curr = this.head;
    while (curr.next && curr.next.value !== value) curr = curr.next;
    if (curr.next) curr.next = curr.next.next;
  }

  toArray() {
    const result = [];
    let curr = this.head;
    while (curr) { result.push(curr.value); curr = curr.next; }
    return result;
  }
}

Complexity vs Array

OperationArrayLinked List
Access by indexO(1)O(n)
PrependO(n)O(1)
AppendO(1) amortizedO(n) (or O(1) with tail pointer)
Delete (by value)O(n)O(n)
Insert at middleO(n)O(1) if you have the node

Your Task

Implement a LinkedList class with append, prepend, delete, and toArray methods.

JavaScript loading...
Loading...
Click "Run" to execute your code.