Ready — add nodes to the list
Speed

🔗 Doubly Linked List

A variation of Linked List in which each node has two pointers: one pointing to the next node and another pointing to the previous node.

⏱ Access: O(n) ⏱ Search: O(n) ⏱ Insertion: O(1)* ⏱ Deletion: O(1)*

*O(1) if you have head/tail reference, otherwise O(n).

Python
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
        self.prev = None

class DoublyLinkedList:
    def __init__(self):
        self.head = None

    def insert_at_head(self, data):
        new_node = Node(data)
        if self.head:
            self.head.prev = new_node
            new_node.next = self.head
        self.head = new_node

    def delete_node(self, node):
        if node.prev:
            node.prev.next = node.next
        else:
            self.head = node.next
        if node.next:
            node.next.prev = node.prev
JavaScript
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
        this.prev = null;
    }
}

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

    insertAtHead(data) {
        const newNode = new Node(data);
        if (this.head) {
            this.head.prev = newNode;
            newNode.next = this.head;
        }
        this.head = newNode;
    }

    deleteNode(node) {
        if (node.prev) node.prev.next = node.next;
        else this.head = node.next;
        if (node.next) node.next.prev = node.prev;
    }
}