-
Notifications
You must be signed in to change notification settings - Fork 0
/
lrucache.go
154 lines (141 loc) · 2.23 KB
/
lrucache.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
)
type node struct {
data int
key int
prev *node
next *node
}
type dlinkedlist struct {
len int
head *node
tail *node
maxCap int
}
type lrucache struct {
hash map[int]*node
list *dlinkedlist
cap int
}
func InitializeLRUCache(cap int) *lrucache {
return &lrucache{
hash: make(map[int]*node, cap),
list: &dlinkedlist{maxCap: cap},
cap: cap,
}
}
func (l *lrucache) Print() {
l.list.PrintList()
fmt.Printf("%+v", l.hash)
fmt.Println(" \n \n ")
}
func (l *lrucache) Add(k, v int) bool {
if nodeaddress, ok := l.hash[k]; ok {
l.list.MoveToFront(nodeaddress, v)
return true
}
if l.list.len >= l.cap {
removedKey := l.list.RemoveTail()
if removedKey != -1 {
delete(l.hash, removedKey)
}
}
add := l.list.Add(k, v)
l.hash[k] = add
return true
}
func (l *lrucache) Delete(k int) {
if nodeaddress, ok := l.hash[k]; ok {
delete(l.hash, k)
l.list.Delete(nodeaddress)
}
}
func (d *dlinkedlist) Add(k int, v int) *node {
n := &node{key: k, data: v}
if d.head == nil {
d.head = n
d.tail = n
} else {
n.next = d.head
d.head.prev = n
d.head = n
}
d.len++
return n
}
func (d *dlinkedlist) Delete(n *node) {
if d.head == n {
d.head = n.next
}
if d.tail == n {
d.tail = n.prev
}
if n.next != nil {
n.next.prev = n.prev
}
if n.prev != nil {
n.prev.next = n.next
}
n = nil
}
func (d *dlinkedlist) MoveToFront(n *node, v int) {
n.data = v
if n.prev == nil {
d.head = n
d.tail = n
return
}
n.prev.next = n.next
n.next.prev = n.prev
n.next = d.head
n.prev = nil
d.head = n
}
func (d *dlinkedlist) PrintList() {
n := d.head
if n == nil {
fmt.Println("list is empty")
}
for n != nil {
fmt.Printf("{ %d , %d } => ", n.key, n.data)
n = n.next
}
fmt.Println(" ")
}
func (d *dlinkedlist) RemoveTail() int {
if d.tail == nil {
return -1
}
n := d.tail
k := n.key
if n.prev == nil {
d.tail = nil
d.head = nil
d.len = 0
return k
}
d.tail = n.prev
d.tail.next = nil
n = nil
d.len--
return k
}
func main() {
l := InitializeLRUCache(3)
l.Add(1, 1)
l.Add(2, 2)
l.Add(3, 2)
l.Add(4, 2)
l.Add(4, 3)
l.Print()
l.Add(4, 4)
l.Print()
l.Add(4, 5)
l.Print()
l.Add(3, 5)
l.Print()
}