LC-146:LRU缓存机制的JS代码是AC不了的
icecai521 opened this issue · comments
我把里面的改完bug后JS代码的贴一下:
class ListNode{
constructor(key, val){
this.key = key;
this.val = val;
this.pre = null;
this.next = null;
}
};
class LRUCache{
constructor(capacity){
this.capacity = capacity;
this.size = 0;
this.data = {};
this.head = new ListNode();
this.tail = new ListNode();
this.head.next = this.tail;
this.tail.pre = this.head;
}
get(key){
if(!this.data[key]) return -1;
else{
let node = this.data[key];
this.removeNode(node);
this.appendHead(node);
return node.val;
}
}
put(key, value){
if(!this.data[key]){
let node = new ListNode(key, value);
this.data[key] = node;
this.appendHead(node);
this.size++;
if(this.size > this.capacity){
const lastKey = this.removeTail();
delete this.data[lastKey];
this.size--;
}
}else{
let node = this.data[key];
this.removeNode(node);
node.val = value;
this.appendHead(node);
}
}
removeNode(node){
let preNode = node.pre;
let nextNode = node.next;
preNode.next = nextNode;
nextNode.pre = preNode;
}
appendHead(node){
let firstNode = this.head.next;
this.head.next = node;
node.pre = this.head;
node.next = firstNode;
firstNode.pre = node;
}
removeTail(){
let key = this.tail.pre.key;
this.removeNode(this.tail.pre);
return key;
}
}
西法哥可以改一下😊
you'r right