javascript
class Node {
constructor(key =0 ,value=0){
this.key=key;
this.value=value;
this.next = null;
this.prev=null;
}
}
class LRUCache{
constructor(capacity){
this.capacity=capacity;
this.dummy=new Node();
this.dummy.next=this.dummy;
this.dummy.prev=this.dummy;
this.idx=new Map();
}
#getNode(key){
if(!this.idx.has(key)) return null;
const node=this.idx.get(key);
this.#remove(node);
this.#pushFront(node);
return node;
}
get(key){
const node=this.#getNode(key);
return node?node.value:-1;
}
put(key,value){
let node=this.#getNode(key);
if(node){
node.value=value;
return ;
}
else{
node=new Node(key,value);
this.idx.set(key,node);
this.#pushFront(node);
}
if(this.idx.size>this.capacity){
const backNode=this.dummy.prev;
this.idx.delete(backNode.key);
this.#remove(backNode);
}
}
#remove(node){
node.prev.next=node.next;
node.next.prev=node.prev;
}
#pushFront(node){
node.prev=this.dummy;
node.next=this.dummy.next;
node.prev.next=node;
node.next.prev=node;
}
}
算法核心:双向链表+哈希
javascript
this.dummy.next=this.dummy;
this.dummy.prev=this.dummy;
node.next=this.dummy.next;
node.next.prev=node;
这样初始化可以保证dummy.prev始终指向尾结点
注意this的使用