LRU缓存(JavaScript)


1. 定义双向链表节点
function DeLinkedNode(key,value){
this.key = key==null?null:key;
this.value = value==null?null:value;
this.next = null;
this.prev = null;
}
2. 定义双向链表
function DeLinked(){
this.head = new DeLinkedNode();
this.tail = new DeLinkedNode();
this.head.next = this.tail;
this.tail.prev = this.head;
this.size = 0;
}
DeLinked.prototype.addToHead = function(node){
node.next = this.head.next;
node.prev = this.head;
this.head.next.prev = node;
this.head.next = node;
this.size++;
}
DeLinked.prototype.moveToHead = function(node) {
this.removeNode(node);
this.addToHead(node);
}
DeLinked.prototype.removeTail = function(){
let res = this.tail.prev;
this.removeNode(res);
return res;
}
DeLinked.prototype.removeNode = function(node){
node.prev.next = node.next;
node.next.prev = node.prev;
this.size--;
}
3. 定义LRU缓存
function LRUcache(capacity){
this.capacity = capacity;
this.map = new Map();
this.deLinked = new DeLinked();
this.size = 0;
}
LRUcache.prototype.get = function(key){
let node = this.map.get(key);
if(node == null){
return -1;
}else{
this.deLinked.moveToHead(node);
return node.value;
}
}
LRUcache.prototype.put = function(key,value){
let node = this.map.get(key);
if(node == null){
let newNode = new DeLinkedNode(key, value);
this.map.set(key, newNode);
this.deLinked.addToHead(newNode);
this.size++;
if(this.size > this.capacity){
let res = this.deLinked.removeTail();
this.map.delete(res.key);
this.size--;
}
}else{
node.value = value;
this.deLinked.moveToHead(node);
}
}