function ListNode(key,val) {
this.key = key
this.val = val
this.next =null
this.prev =null
}
var LRUCache = function (capacity) {
this.hash = {}
this.capacity = capacity
this.head = new ListNode()
this.tail = new ListNode()
this.head.next = this.tail
this.tail.prev = this.head
this.length = 0
};
LRUCache.prototype.get = function (key) {
let n = this.hash[key]
if(n!=undefined){
this.moveToHead(n)
return n.val
}
return -1
};
LRUCache.prototype.put = function (key, value) {
let node = new ListNode(key, value)
let n = this.hash[key]
if(n){
this.removeNode(n)
this.addToHead(node)
}else{
if (this.length >= this.capacity) {
delete this.hash[this.tail.prev.key]
this.removeNode(this.tail.prev)
} else {
this.length++
}
this.addToHead(node)
}
this.hash[key] = node
};
LRUCache.prototype.moveToHead = function(node){
this.removeNode(node)
this.addToHead(node)
}
LRUCache.prototype.removeNode = function (node) {
node.prev.next = node.next
node.next.prev = node.prev
}
LRUCache.prototype.addToHead = function (node) {
node.next = this.head.next
node.next.prev = node
node.prev = this.head
this.head.next = node
}