-
Notifications
You must be signed in to change notification settings - Fork 87
/
Copy pathfifo.go
80 lines (71 loc) · 1.9 KB
/
fifo.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
package Cache
import (
"github.com/yezihack/math/DoubleLinedList"
)
/* FIFO(first in first out) 先进先出淘汰算法*/
/*
解题思路:
1. 借用双链表实现FIFO
2. 借用map实现缓存, 避免对链表的搜索
*/
//定义FIFO的结构体
type FIFOCache struct {
double *DoubleLinedList.DoubleList
cache map[int]*DoubleLinedList.DoubleNode
}
//实例对象
func NewFIFO(capacity uint) *FIFOCache {
fifo := FIFOCache{}
fifo.double = DoubleLinedList.New(capacity)
fifo.cache = make(map[int]*DoubleLinedList.DoubleNode)
return &fifo
}
//获取值
func (f *FIFOCache) Get(key int) *DoubleLinedList.DoubleNode {
//判断是否在缓存中
if node, ok := f.cache[key]; ok { //存在的话
return node
} else { //不存在的话
return nil
}
}
//添加元素
func (f *FIFOCache) Put(key int, data interface{}) bool {
//判断是否存在缓存中
if node, ok := f.cache[key]; ok { //存在的话
//更新数据,删除链表, 再添加到链表中
node.Value = data
f.double.Remove(node)
f.double.Append(node)
} else { //不存在的话
////判断容量是否满了
//if f.double.Size >= f.double.Capacity { //满了.
// //删除头部数据,因为我们是追加, 头部数据是最早添加的
// f.double.RemoveHead()
// node = DoubleLinedList.Node(key, data)
// f.double.Append(node)
// f.cache[key] = node
//} else { //没满
// node = DoubleLinedList.Node(key, data)
// f.double.Append(node)
// f.cache[key] = node
//}
/**************将以上逻辑简化*****************/
if f.double.Size >= f.double.Capacity { //满了.
//删除头部数据,因为我们是追加, 头部数据是最早添加的
f.double.RemoveHead()
}
node = DoubleLinedList.Node(key, data)
f.double.Append(node)
f.cache[key] = node
}
return true
}
//获取链表大小
func (f *FIFOCache) GetSize() uint {
return f.double.Size
}
//打印
func (f *FIFOCache) Print() {
f.double.Print()
}