Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Written by Array Alchemist
LeetCode wizard with 75 conquered challenges under my belt.
Turning algorithm nightmares into "Aha!" moments, one explanation at a time.
Join me to level up your coding skills – from interviews to real-world application!
A normal linked list:
{ this.key this.val this.next }What Is a Doubly Linked List?
A doubly linked list is a type of data structure made up of nodes. Each node contains:
Unlike a singly linked list, where each node only points to the next node, a DLL allows traversal in both directions.
{ this.key this.val this.next this.prev }Adding a node:
Why Use a Doubly Linked List?
class Node { constructor(key, val) { this.val = val this.next = null this.prev = null this.key = key } } class LRUCache { /** * @param {number} capacity */ constructor(capacity) { this.cache = new Map() this.capacity = capacity this.head = new Node(0, 0) this.tail = new Node(0, 0) this.head.next = this.tail this.tail.prev = this.head } _remove(node) { // 0 -> lru -> 1 node.prev.next = node.next node.next.prev = node.prev } _addToFront(node) { //head -> node -> normalNext node.next = this.head.next node.prev = this.head this.head.next.prev = node this.head.next = node } get(key) { /* If the key exists, return its value & mark it as recently used. If the key does not exist, return -1. */ // we take access the current Node // put it next to current head // if key doesn't exist return -1 if (!this.cache.has(key)) { return -1 } const currentNode = this.cache.get(key) this._remove(currentNode) this._addToFront(currentNode) // now our list head's next should be this node return currentNode.val } put(key, value) { // when we update the cahce, put the recent ones closer to head if (this.cache.has(key)) { const node = this.cache.get(key) node.val = value this._remove(node) this._addToFront(node) return } // now how do we handle the capacity if (this.cache.size >= this.capacity) { // now our list head's next should be this node const lru = this.tail.prev this._remove(lru) this.cache.delete(lru.key) } const newNode =new Node(key,value) this._addToFront(newNode) this.cache.set(key, newNode) } }