image.png
    image.png

    Go 语言需要自己创建双向链表,推荐创建2个哨兵节点

    1. package main
    2. import "fmt"
    3. type Node struct {
    4. key int
    5. value int
    6. pre *Node
    7. next *Node
    8. }
    9. type LRUCache struct {
    10. m map[int] *Node
    11. head *Node
    12. tail *Node
    13. capacity int
    14. }
    15. func Constructor(capacity int) LRUCache {
    16. cache := LRUCache{
    17. m: make(map[int]*Node),
    18. head: &Node{},
    19. tail: &Node{},
    20. capacity: capacity,
    21. }
    22. cache.head.next = cache.tail
    23. cache.tail.pre = cache.head
    24. return cache
    25. }
    26. // 头部添加元素
    27. func (this *LRUCache)AddHead(n *Node){
    28. tmp := this.head.next
    29. this.head.next = n
    30. n.next = tmp
    31. n.pre = this.head
    32. tmp.pre = n
    33. }
    34. func (this *LRUCache)RemoveNode(n *Node){
    35. pre := n.pre
    36. next := n.next
    37. pre.next = next
    38. next.pre = pre
    39. n.pre = nil
    40. n.next = nil
    41. }
    42. func (this *LRUCache) Get(key int) int {
    43. node ,ok:= this.m[key]
    44. if ok {
    45. this.RemoveNode(node)
    46. this.AddHead(node)
    47. return node.value
    48. }
    49. return -1
    50. }
    51. func (this *LRUCache) Put(key int, value int) {
    52. node ,ok:= this.m[key]
    53. if ok {// 存在
    54. if node.value!= value {
    55. node.value = value
    56. }
    57. this.RemoveNode(node)
    58. this.AddHead(node)
    59. }else {
    60. n := &Node{
    61. key:key,
    62. value: value,
    63. }
    64. if this.capacity==len(this.m) {// 删除
    65. delete(this.m,this.tail.pre.key)
    66. this.RemoveNode(this.tail.pre)
    67. }
    68. this.AddHead(n)
    69. this.m[key] = n
    70. }
    71. }
    72. func main() {
    73. cache := Constructor(2)
    74. cache.Put(1,1)
    75. cache.Put(2,2)
    76. fmt.Println(cache.Get(1))//1
    77. cache.Put(3,3)
    78. fmt.Println(cache.Get(2))//-1
    79. cache.Put(4,4)
    80. fmt.Println(cache.Get(1))//-1
    81. fmt.Println(cache.Get(3))//3
    82. fmt.Println(cache.Get(4))//4
    83. }