使用go实现LRU

是一道练习数据结构的好题,主要是为了练习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)
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值