// 双向链表节点var LinkNode = function (key, val) { if(!(this instanceof LinkNode)) { return new LinkNode(key, val) } this.key = key; this.val = val;}// 双向链表var DoubleLink = function() { this.head = new LinkNode(0, 0) this.tail = new LinkNode(0, 0) this.head.next = this.tail this.tail.prev = this.head this.size = 0}// // 在链表尾部添加节点 x,时间 O(1)DoubleLink.prototype.addLast = function(node) { node.prev = this.tail.prev node.next = this.tail this.tail.prev.next = node this.tail.prev = node ++this.size}// 删除链表中的 x 节点(x 一定存在)// 由于是双链表且给的是目标 Node 节点,时间 O(1)DoubleLink.prototype.remove = function (node) { node.prev.next = node.next; node.next.prev = node.prev; --this.size;}// 删除链表中第一个节点,并返回该节点,时间 O(1)DoubleLink.prototype.removeFirst = function() { if(this.head.next === this.tail) { return null } let first = this.head.next this.remove(first) return first}// 返回链表长度,时间 O(1)DoubleLink.prototype.getSize = function () { return this.size;}/** * @param {number} capacity */var LRUCache = function (capacity) { this.map = new Map(); this.cache = new DoubleLink(); //最大容量 this.cap = capacity;};/** * @param {number} key * @return {number} */LRUCache.prototype.get = function (key) { if (!this.map.has(key)) { return -1; } // 将该数据提升为最近使用的 this.makeRecently(key); return this.map.get(key).val;};/** * @param {number} key * @param {number} value * @return {void} */LRUCache.prototype.put = function (key, value) { if (this.map.has(key)) { // 删除旧的数据 this.deleteKey(key); // 新插入的数据为最近使用的数据 this.addRecently(key, value); return; } if (this.cap === this.cache.getSize()) { // 删除最久未使用的元素 this.removeLeastRecently(); } // 添加为最近使用的元素 this.addRecently(key, value);};/** * Your LRUCache object will be instantiated and called as such: * var obj = new LRUCache(capacity) * var param_1 = obj.get(key) * obj.put(key,value) *//* 将某个 key 提升为最近使用的 */LRUCache.prototype.makeRecently = function (key) { let x = this.map.get(key); // 先从链表中删除这个节点 this.cache.remove(x); // 重新插入到队尾 this.cache.addLast(x);}/* 添加最近使用的元素 */LRUCache.prototype.addRecently = function (key, val) { let x = new LinkNode(key, val); // 链表尾部就是最近使用的元素 this.cache.addLast(x); // 别忘了在 map 中添加 key 的映射 this.map.set(key, x);}/* 删除某一个 key */LRUCache.prototype.deleteKey = function (key) { let x = this.map.get(key); // 从链表中删除 this.cache.remove(x); // 从 map 中删除 this.map.delete(key);}/* 删除最久未使用的元素 */LRUCache.prototype.removeLeastRecently = function () { // 链表头部的第一个元素就是最久未使用的 let deletedNode = this.cache.removeFirst(); // 同时别忘了从 map 中删除它的 key let deletedKey = deletedNode.key; this.map.delete(deletedKey);}