1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| package main
import "fmt"
type LRUCache struct { capacity int cache map[int]*Node head *Node tail *Node }
type Node struct { key int value int prev *Node next *Node }
func Constructor(capacity int) LRUCache { return LRUCache{ capacity: capacity, cache: make(map[int]*Node), head: nil, tail: nil, } }
func (lru *LRUCache) get(key int) int { if node, ok := lru.cache[key]; ok { lru.moveToHead(node) return node.value } return -1 }
func (lru *LRUCache) put(key, value int) { if node, ok := lru.cache[key]; ok { node.value = value lru.moveToHead(node) } else { node := &Node{key: key, value: value} lru.cache[key] = node
if len(lru.cache) > lru.capacity { lru.removeTail() }
lru.addToHead(node) } }
func (lru *LRUCache) moveToHead(node *Node) { if node != lru.head { lru.removeNode(node) lru.addToHead(node) } }
func (lru *LRUCache) removeNode(node *Node) { if node.prev != nil { node.prev.next = node.next } else { lru.head = node.next }
if node.next != nil { node.next.prev = node.prev } else { lru.tail = node.prev } }
func (lru *LRUCache) addToHead(node *Node) { node.prev = nil node.next = lru.head
if lru.head != nil { lru.head.prev = node }
lru.head = node
if lru.tail == nil { lru.tail = node } }
func (lru *LRUCache) removeTail() { if lru.tail != nil { delete(lru.cache, lru.tail.key) lru.removeNode(lru.tail) } }
func main() { lru := Constructor(2)
lru.put(1, 1) lru.put(2, 2)
fmt.Println("查询键 1 的结果:", lru.get(1))
lru.put(3, 3)
fmt.Println("查询键 2 的结果:", lru.get(2))
lru.put(4, 4)
fmt.Println("查询键 1 的结果:", lru.get(1))
fmt.Println("查询键 3 的结果:", lru.get(3))
fmt.Println("查询键 4 的结果:", lru.get(4)) }
|