prep4place
Back to Visualizer

Linked List

A linear data structure where elements are stored in nodes, each pointing to the next node. Allows dynamic memory allocation and efficient insertions/deletions.

Insert: O(1) at headSearch: O(n)
Speed:
HEAD →
idx: 0
10
next
idx: 1
20
next
idx: 2
30
next
idx: 3
40
next
→ NULL
Default
Current
Found
New
Deleting
4
Nodes in List

Operations

  • Insert at Head: O(1)
  • Insert at Tail: O(n)
  • Insert at Position: O(n)
  • Delete from Head: O(1)
  • Delete from Tail: O(n)
  • Search: O(n)
  • Reverse: O(n)

Complexity

AccessO(n)
SearchO(n)
Insert (head)O(1)
Delete (head)O(1)
SpaceO(n)

Code

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

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

  insertAtHead(value) {
    const node = new Node(value);
    node.next = this.head;
    this.head = node;
  }

  insertAtTail(value) {
    const node = new Node(value);
    if (!this.head) {
      this.head = node;
      return;
    }
    let current = this.head;
    while (current.next) {
      current = current.next;
    }
    current.next = node;
  }

  deleteFromHead() {
    if (this.head) {
      this.head = this.head.next;
    }
  }

  search(value) {
    let current = this.head;
    let index = 0;
    while (current) {
      if (current.value === value) {
        return index;
      }
      current = current.next;
      index++;
    }
    return -1;
  }
}