1. package main
    2. type Node struct {
    3. key, value int
    4. prev, next *Node
    5. }
    6. type LRUCache struct {
    7. capacity int
    8. head, tail *Node
    9. cache map[int]*Node
    10. }
    11. func Constructor(capacity int) LRUCache {
    12. head, tail := &Node{}, &Node{}
    13. head.next = tail
    14. tail.prev = head
    15. return LRUCache{
    16. capacity: capacity,
    17. head: head,
    18. tail: tail,
    19. cache: make(map[int]*Node),
    20. }
    21. }
    22. func (t *LRUCache) Get(key int) int {
    23. node, exist := t.cache[key]
    24. if !exist {
    25. return -1
    26. }
    27. t.remove(node)
    28. t.insert(node)
    29. return node.value
    30. }
    31. func (t *LRUCache) Put(key int, value int) {
    32. if node, exist := t.cache[key]; exist {
    33. t.remove(node)
    34. t.insert(&Node{
    35. key: key,
    36. value: value,
    37. })
    38. return
    39. }
    40. if len(t.cache) == t.capacity {
    41. t.remove(t.head.next)
    42. }
    43. t.insert(&Node{
    44. key: key,
    45. value: value,
    46. })
    47. }
    48. func (t *LRUCache) insert(node *Node) {
    49. node.prev = t.tail.prev
    50. node.next = t.tail
    51. t.tail.prev.next = node
    52. t.tail.prev = node
    53. t.cache[node.key] = node
    54. }
    55. func (t *LRUCache) remove(node *Node) {
    56. node.prev.next = node.next
    57. node.next.prev = node.prev
    58. delete(t.cache, node.key)
    59. }