-
Notifications
You must be signed in to change notification settings - Fork 0
/
lru_cache.go
111 lines (91 loc) · 1.67 KB
/
lru_cache.go
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
/*
This is a LRU cache
*/
package main
import (
"fmt"
)
const SIZE = 5 // size of cache
type Node struct {
Val string
Left *Node
Right *Node
}
// double linked list
type Queue struct {
Head *Node
Tail *Node
Length int
}
// maps string to node in Queue
type Hash map[string]*Node
type Cache struct {
Queue Queue
Hash Hash
}
func NewCache() Cache {
return Cache{Queue: NewQueue(), Hash: Hash{}}
}
func NewQueue() Queue {
head := &Node{}
tail := &Node{}
head.Right = tail
tail.Left = head
return Queue{Head: head, Tail: tail}
}
func (c *Cache) Check(str string) {
node := &Node{}
if val, ok := c.Hash[str]; ok {
node = c.Remove(val)
} else {
node = &Node{Val: str}
}
c.Add(node)
c.Hash[str] = node
}
func (c *Cache) Remove(n *Node) *Node {
fmt.Printf("remove: %s\n", n.Val)
left := n.Left
right := n.Right
left.Right = right
right.Left = left
c.Queue.Length -= 1
delete(c.Hash, n.Val)
return n
}
func (c *Cache) Add(n *Node) {
fmt.Printf("add: %s\n", n.Val)
tmp := c.Queue.Head.Right
c.Queue.Head.Right = n
n.Left = c.Queue.Head
n.Right = tmp
tmp.Left = n
c.Queue.Length++
if c.Queue.Length > SIZE {
c.Remove(c.Queue.Tail.Left)
}
}
func (c *Cache) Display() {
c.Queue.Display()
}
func (q *Queue) Display() {
node := q.Head.Right
fmt.Printf("%d - [", q.Length)
for i := 0; i < q.Length; i++ {
fmt.Printf("{%s}", node.Val)
if i < q.Length-1 {
fmt.Printf(" <--> ")
}
node = node.Right
}
fmt.Println("]")
}
func main() {
fmt.Println("START CACHE")
cache := NewCache()
for _, word := range []string{"cat", "blue", "dog", "tree", "dragon",
"potato", "house", "tree", "cat"} {
cache.Check(word)
cache.Display()
}
}