Back

Linked List Visualization

Interactive Demonstration

Visualize common Singly Linked List operations.

O(1)
O(n)
Head
NULL
O(n)
O(n)
O(n)

Add nodes or perform operations on the linked list.

How Linked Lists Work

A singly linked list is a linear data structure where elements are not stored at contiguous memory locations. Instead, elements are linked using pointers.

Example Implementation (Conceptual)

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

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

    // Add to head - O(1)
    addHead(data) {
        const newNode = new Node(data);
        newNode.next = this.head;
        this.head = newNode;
    }

    // Add to tail - O(n)
    addTail(data) {
        const newNode = new Node(data);
        if (!this.head) {
            this.head = newNode;
            return;
        }
        let current = this.head;
        while (current.next) {
            current = current.next;
        }
        current.next = newNode;
    }

    // Delete node by value - O(n)
    delete(data) {
        if (!this.head) return false;

        if (this.head.data === data) {
            this.head = this.head.next;
            return true;
        }

        let current = this.head;
        while (current.next && current.next.data !== data) {
            current = current.next;
        }

        if (current.next) { // Found the node before the one to delete
            current.next = current.next.next;
            return true;
        }
        return false; // Not found
    }

    // Search for value - O(n)
    search(data) {
        let current = this.head;
        while (current) {
            if (current.data === data) {
                return current; // Return the node if found
            }
            current = current.next;
        }
        return null; // Not found
    }
}