commit 6546085403540bd5a4095a1761f3787e47996130 Author: Your Name Date: Fri Jul 16 10:06:22 2021 +0800 init diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..73f69e0 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/.idea/LRUCache.iml b/.idea/LRUCache.iml new file mode 100644 index 0000000..5e764c4 --- /dev/null +++ b/.idea/LRUCache.iml @@ -0,0 +1,9 @@ + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..9d8483f --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..94a25f7 --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f5a222e --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/doublepi123/LRUCache + +go 1.14 diff --git a/lru.go b/lru.go new file mode 100644 index 0000000..761851f --- /dev/null +++ b/lru.go @@ -0,0 +1,42 @@ +package LRUCache + +import "container/list" + +type item struct { + key string + value string + pos *list.Element +} + +type LRU struct { + ul list.List + data map[string]*item + Maxsize int +} + +func (lru LRU) Get(key string) string { + i := lru.data[key] + if i != nil { + lru.ul.Remove(i.pos) + lru.ul.PushBack(i) + return i.value + } else { + return "" + } +} + +func (lru LRU) Set(key string, value string) { + i := &item{key: key, value: value} + lru.data[key] = i + lru.ul.Remove(i.pos) + lru.ul.PushBack(i) + if lru.ul.Len() > lru.Maxsize { + lru.ul.Remove(lru.ul.Front()) + } + i.pos = lru.ul.Back() +} + +func (lru LRU) init() { + lru.data = make(map[string]*item) + lru.ul = list.List{} +}