-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlru.go
77 lines (71 loc) · 1.4 KB
/
lru.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
package godata
import "container/list"
type LRUCache struct {
Cache map[int]*list.Element
Cap int
List *list.List
}
type LRUNode struct {
Key, Value int
}
//new a LRU
func NewLRU(capacity int) LRUCache {
return LRUCache{
Cache: make(map[int]*list.Element),
Cap: capacity,
List: list.New(),
}
}
// Rebuild the LRU.
func(l *LRUCache)ReBuild(){
l.List.Init()
l.Cache = make(map[int]*list.Element)
}
// exist:value, no:-1
func (l *LRUCache) Get(key int) int {
v, ok := l.Cache[key]
if ok {
l.List.MoveToFront(v)
return v.Value.(*LRUNode).Value
}
// top the LRUNode
return -1
}
// put a new data
func (l *LRUCache) Put(key int, value int) {
if l.List.Len() < l.Cap {
if v, ok := l.Cache[key]; ok {
// if has key and match value.
if v.Value.(*LRUNode).Value != value {
v.Value.(*LRUNode).Value = value
}
l.List.MoveToFront(v)
// the key is not match value
} else {
n := &LRUNode{
Key: key,
Value: value,
}
el := l.List.PushFront(n)
l.Cache[key] = el
}
} else {
if v, ok := l.Cache[key]; ok {
// if has key and match value.
if v.Value.(*LRUNode).Value != value {
v.Value.(*LRUNode).Value = value
}
l.List.MoveToFront(v)
} else {
tti := l.List.Back()
delete(l.Cache, tti.Value.(*LRUNode).Key)
l.List.Remove(tti)
n := &LRUNode{
Key: key,
Value: value,
}
el := l.List.PushFront(n)
l.Cache[key] = el
}
}
}