1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
| interface Node<K, V> { key: K; value: V; prev: Node<K, V> | null; next: Node<K, V> | null; }
class LRUCache<K = number, V = number> { private capacity: number; private cache: Map<K, Node<K, V>>; private head: Node<K, V>; private tail: Node<K, V>;
constructor(capacity: number) { this.capacity = capacity; this.cache = new Map<K, Node<K, V>>(); this.head = { key: null as any, value: null as any, prev: null, next: null }; this.tail = { key: null as any, value: null as any, prev: null, next: null }; this.head.next = this.tail; this.tail.prev = this.head; }
private moveToHead(node: Node<K, V>): void { node.prev!.next = node.next; node.next!.prev = node.prev!;
node.next = this.head.next; node.prev = this.head; this.head.next!.prev = node; this.head.next = node; }
private removeTail(): Node<K, V> { const lastNode = this.tail.prev!; lastNode.prev!.next = this.tail; this.tail.prev = lastNode.prev; return lastNode; }
get(key: K): V | -1 { const node = this.cache.get(key); if (!node) { return -1; } this.moveToHead(node); return node.value; }
put(key: K, value: V): void { const existingNode = this.cache.get(key);
if (existingNode) { existingNode.value = value; this.moveToHead(existingNode); } else { const newNode: Node<K, V> = { key, value, prev: null, next: null }; this.cache.set(key, newNode);
newNode.next = this.head.next; newNode.prev = this.head; this.head.next!.prev = newNode; this.head.next = newNode;
if (this.cache.size > this.capacity) { const tailNode = this.removeTail(); this.cache.delete(tailNode.key); } } }
printCache(): void { const result: string[] = []; let current = this.head.next; while (current !== this.tail) { result.push(`${current!.key}:${current!.value}`); current = current!.next; } console.log('LRU Cache:', result.join(' -> ')); } }
const cache = new LRUCache<number, number>(3); cache.put(1, 1); cache.put(2, 2); cache.put(3, 3); cache.printCache(); console.log(cache.get(2)); cache.printCache();
|