是一道练习数据结构的好题,主要是为了练习Go语法,折腾了半个多小时,踩了一些坑,else不能单独放在一行,map需要初始化后才可以使用,实现如下
构建了双向链表,建立了头结点head与尾节点tail,
实现了erase接口与push_front接口
type ListNode struct{
key int
val int
pre*ListNode
next*ListNode
}
type LRUCache struct {
vol int
ma map[int]*ListNode
head*ListNode//头结点,固定
tail*ListNode//尾结点,固定
}
func Constructor(capacity int) LRUCache {
h:= ListNode{-1,0,nil,nil}
t:= ListNode{-1,0,nil,nil}
h.next = &t
t.pre = &h
lru:= LRUCache{capacity,make(map[int]*ListNode,capacity),&h,&t}
return lru
}
func (this*LRUCache) erase(cur*ListNode){
pre,next:= cur.pre,cur.next
pre.next,next.pre = next,pre
}
func (this*LRUCache) push_front(cur*ListNode){
prehead:= this.head.next
cur.next = prehead
cur.pre = this.head
prehead.pre = cur
this.head.next = cur
}
func (this *LRUCache) Get(key int) int {
cur,exist:= this.ma[key]
if(exist){
this.erase(cur)
this.push_front(cur)
return cur.val
}else{
return -1
}
}
func (this *LRUCache) Put(key int, value int) {
cur,exist:= this.ma[key]
if(exist){
cur.val = value
this.erase(cur)
this.push_front(cur)
}else{
if(len(this.ma) == this.vol){
tail:= this.tail.pre
this.erase(tail)
delete(this.ma,tail.key)
}
newNode :=ListNode{key,value,nil,nil}
this.ma[key] = &newNode
this.push_front(&newNode)
}
}