Code Snippets
/

Singly Linked List Template

Singly Linked List Template

Linked lists rarely beat arrays in production JavaScript, but they are the single most-asked interview data structure and the conceptual foundation for skip lists, LRU caches, and queue implementations. This snippet covers the Node + List skeleton with O(1) prepend, an O(n) traversal helper, and the in-place reverse that shows up in nearly every interview round.

JavaScript
Medium
3 snippets
data-structures
linked-list
code-template
algorithms

1,134 views

16

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

class LinkedList {
    constructor() { this.head = null; this.size = 0; }
    prepend(value) {
        this.head = new ListNode(value, this.head);
        this.size++;
        return this;
    }
    toArray() {
        const out = [];
        for (let n = this.head; n !== null; n = n.next) out.push(n.value);
        return out;
    }
}

const list = new LinkedList();
list.prepend(3).prepend(2).prepend(1);
console.log(list.toArray()); // [1, 2, 3]
console.log(list.size);      // 3

A singly linked list is a chain of Node { value, next } cells where the list itself stores only a head pointer. Prepending in O(1) is the linked list's headline win over arrays: build a new node whose next points at the current head, then reseat head. The toArray helper makes the list inspectable in tests and the chained prepend mirrors immutable list APIs from functional languages. Storing size is optional but pays for itself the first time a caller asks for length.