publicvoidremoveNode(Node node){ if (node.key==tail.key) { tail=tail.pre; return; } if (node.pre==null || node.next==null) { return; } node.pre.next=node.next; node.next.pre=node.pre; }
publicvoidmove2Head(Node newHead){ if (map.size()==0) { head=tail=newHead; return; } if (newHead.key==head.key) { return; } removeNode(newHead); newHead.next=head; newHead.pre=null; head.pre=newHead; head=newHead; } }
/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
/** * Your LRUCache object will be instantiated and called as such: * LRUCache obj = new LRUCache(capacity); * int param_1 = obj.get(key); * obj.put(key,value); */
Golang
type LRUCache struct { capacity int cache map[int]*Node head *Node tail *Node }
type Node struct { prev *Node next *Node key int val int }
funcConstructor(capacity int) LRUCache { head := &Node{key : -1, val : -1} tail := &Node{key : -1, val : -1} head.next = tail tail.next = head return LRUCache{ capacity : capacity, cache : make(map[int]*Node), head : head, tail : tail, } }
func(this *LRUCache) Get(key int) int { if v, ok := this.cache[key]; ok { this.removeNode(v) this.insert2Head(v) return v.val } return-1 }
func(this *LRUCache) Put(key int, value int) { if v, ok := this.cache[key]; ok { this.removeNode(v) v.val = value this.insert2Head(v) } else { newNode := &Node{key : key, val : value} this.cache[key] = newNode this.insert2Head(newNode) } iflen(this.cache) > this.capacity { delete(this.cache, this.tail.prev.key) this.removeNode(this.tail.prev) } }
/** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */