-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlru.go
64 lines (55 loc) · 1.07 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
package main
type Node struct {
key, value int
next, prev *Node
}
type LRUCache struct {
cap int
mp map[int]*Node
head, tail *Node
}
func NewLRUCache(capacity int) *LRUCache {
lru := &LRUCache{
cap: capacity,
mp: map[int]*Node{},
head: &Node{},
tail: &Node{},
}
lru.head.next = lru.tail
lru.tail.prev = lru.head
return lru
}
func (l *LRUCache) Get(key int) int {
val := -1
n, found := l.mp[key]
if found {
val = n.value
l.delete(n)
l.insert(n)
}
return val
}
func (l *LRUCache) Put(key, value int) {
n, found := l.mp[key]
if found {
l.delete(n)
l.insert(&Node{key: key, value: value})
} else {
if l.cap == len(l.mp) {
l.delete(l.tail.prev)
}
l.insert(&Node{key: key, value: value})
}
}
func (l *LRUCache) insert(node *Node) {
l.mp[node.key] = node
node.next = l.head.next
node.next.prev = node
node.prev = l.head
l.head.next = node
}
func (l *LRUCache) delete(node *Node) {
delete(l.mp, node.key)
node.prev.next = node.next
node.next.prev = node.prev
}