-
Notifications
You must be signed in to change notification settings - Fork 2
/
146_2_LRU_cache.go
71 lines (64 loc) · 1.28 KB
/
146_2_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
package linked_list
type LRUCacheWorking struct {
head, tail *NodeA
Keys map[int]*NodeA
Cap int
}
type NodeA struct {
Key, Val int
Prev, Next *NodeA
}
func Constructor(capacity int) LRUCacheWorking {
return LRUCacheWorking{Keys: make(map[int]*NodeA), Cap: capacity}
}
func (this *LRUCacheWorking) Get(key int) int {
if node, ok := this.Keys[key]; ok {
this.Remove(node)
this.Add(node)
return node.Val
}
return -1
}
func (this *LRUCacheWorking) Put(key int, value int) {
if node, ok := this.Keys[key]; ok {
node.Val = value
this.Remove(node)
this.Add(node)
return
} else {
node = &NodeA{Key: key, Val: value}
this.Keys[key] = node
this.Add(node)
}
if len(this.Keys) > this.Cap {
delete(this.Keys, this.tail.Key)
this.Remove(this.tail)
}
}
func (this *LRUCacheWorking) Add(node *NodeA) {
node.Prev = nil
node.Next = this.head
if this.head != nil {
this.head.Prev = node
}
this.head = node
if this.tail == nil {
this.tail = node
this.tail.Next = nil
}
}
func (this *LRUCacheWorking) Remove(node *NodeA) {
if node == this.head {
this.head = node.Next
node.Next = nil
return
}
if node == this.tail {
this.tail = node.Prev
node.Prev.Next = nil
node.Prev = nil
return
}
node.Prev.Next = node.Next
node.Next.Prev = node.Prev
}