Skip to content

Commit 315a5f2

Browse files
committed
ts-3: lru cavhe
1 parent b6281d8 commit 315a5f2

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

typescript/Linked Lists/lru_cache.ts

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
class DoublyLinkedListNode {
2+
key: number; val: number;
3+
prev: DoublyLinkedListNode | null;
4+
next: DoublyLinkedListNode | null;
5+
6+
constructor(key: number, val: number) {
7+
this.key = key;
8+
this.val = val;
9+
this.prev = null;
10+
this.next = null;
11+
}
12+
}
13+
14+
class LRUCache {
15+
capacity: number;
16+
hashmap: Map<number, DoublyLinkedListNode>;
17+
head: DoublyLinkedListNode; tail: DoublyLinkedListNode;
18+
19+
constructor(capacity: number) {
20+
this.capacity = capacity;
21+
// A hash map that maps keys to nodes.
22+
this.hashmap = new Map();
23+
// Initialize the head and tail dummy nodes and connect them to
24+
// each other to establish a basic two-node doubly linked list.
25+
this.head = new DoublyLinkedListNode(-1, -1);
26+
this.tail = new DoublyLinkedListNode(-1, -1);
27+
this.head.next = this.tail;
28+
this.tail.prev = this.head;
29+
}
30+
31+
get(key: number): number {
32+
if (!this.hashmap.has(key))
33+
return -1;
34+
// To make this key the most recently used, remove its node and
35+
// re-add it to the tail of the linked list.
36+
const node = this.hashmap.get(key)!;
37+
this.removeNode(node);
38+
this.addToTail(node);
39+
return node.val;
40+
}
41+
42+
put(key: number, val: number): void {
43+
// If a node with this key already exists, remove it from the
44+
// linked list.
45+
if (this.hashmap.has(key))
46+
this.removeNode(this.hashmap.get(key)!);
47+
const node = new DoublyLinkedListNode(key, val);
48+
this.hashmap.set(key, node);
49+
// Remove the least recently used node from the cache if adding
50+
// this new node will result in an overflow.
51+
if (this.hashmap.size > this.capacity) {
52+
this.hashmap.delete(this.head.next!.key);
53+
this.removeNode(this.head.next!);
54+
}
55+
this.addToTail(node);
56+
}
57+
58+
addToTail(node: DoublyLinkedListNode): void {
59+
const prevNode = this.tail.prev;
60+
node.prev = prevNode;
61+
node.next = this.tail;
62+
prevNode!.next = node;
63+
this.tail.prev = node;
64+
}
65+
66+
removeNode(node: DoublyLinkedListNode): void {
67+
node.prev!.next = node.next;
68+
node.next!.prev = node.prev;
69+
}
70+
}

0 commit comments

Comments
 (0)