设计实现一个LRU Cache Golang版本

2023-08-20
1分钟阅读时长

设计实现一个LRU Cache Golang版本

type LRUCache struct {
	capacity int
	m        map[int]*Node
	cache    *ListNode
}

type Node struct {
	key   int
	value int
	prev  *Node
	next  *Node
}

func initNode(key, value int) *Node {
	return &Node{
		key:   key,
		value: value,
	}
}

type NodeList struct {
	head *Node
	last *Node
	size int
}

func initNodeList() *NodeList {
	dial := &NodeList{
		head: initNode(0, 0),
		last: initNode(0, 0),
		size: 0,
	}
	dial.last.next = dial.last
	dial.head.prev = dial.head
	return dial
}

func Constructor(capacity int) *LRUCache {
	return &LRUCache{
		capacity: capacity,
		m:        make(map[int]*Node),
		cache:    initNodeList(),
	}
}

func (this *NodeList) addNodeinlist(node *Node) {
	node.prev = this.last.prev
	this.last.prev = node
	node.next = nil
	node.prev = nil
	this.size++
}

func (this *NodeList) deleteNodeinlist(node *Node) {
	node.prev.next = node.next
	node.next.prev = node.prev
	node.next = nil
	node.prev = nil
	this.size--
}

func (this *NodeList) delfirstNode() *Node{
	if this.head.next = this.last{
		return nil
	}
	t := this.head.next
	this.deleteNodeinlist(t)
	return t
}

func (this *LRUCache) addkey(key int) {
	node := initNode(key,value)
	this.m[key] =node
	this.cache.addNodeinlist(node)
}

func (this *LRUCache) makekey(key int) {
	node := this.m[key]
	this.cache.deleteNodeinlist(node)
	this.cache.addNodeinlist(node)
}

func (this *LRUCache) deletefirkey() {
	node := this.cache.delfirstNode()
	delete(this.m,node.key)
}

func (this *LRUCache) deletekey(key int) {
	this.cache.deleteNodeinlist(this.m[key])
}

func (this *LRUCache) Get(key int) int {
	if _,ok := this.m[key];ok{
		this.makekey(key)
		return this.m[key].value
	}else{
		return -1
	}

}
func (this *LRUCache) Put(key, value int) {
	if _,ok := this.m[key];ok{
		this.deletekey(key)
		this.addkey(key,value)
	}else{
		if this.capacity == this.cache.size{
			this.deletefirkey()
		}
		this.addkey(key,value)
	}
}

本主题指南

技术实践与开发文档
  • 深入探究一下Kubernetes Operator Pattern,为CustomResourceDefinition使用贡献有效经验

    Kubernetes让部署和无感知扩容变的异常简单。如果实操,基本上只需要在YAML文件中把相关联的应用的参数做下指定即可,然后提交给Kubernetes系统识别你的声明式指令,Kubernetes内建的状态循环机制就会自动的创建或者销毁相应资源,来把集群调整到我预设的状态上来,一切都如此轻松!

  • 如何从头创建一个KubernetesOperator

    对于什么是`controller`什么是`operator`可能大家有比较多的迷惑,特别对于你不是做`Kubernetes`领域相关工作的,可能就更像听天书。简明扼要给出我的理解,`operators`是一种特别的`controller`。区别在于`operators`中针对于`controller`可能会包含进更多特定的负载相关的知识。 那么下个问题就出现了,什么是`controller`?

  • Client Go四种交互模式之 DynamicClient实战案例详解

    Client Go四种交互模式之 DynamicClient实战案例详解

  • 对于kubernetes体系课的录制自己的一些思考

    由于天天要搞的事情太多,所以准备录云原生kubernetes课程的事情一拖再拖!但好消息是这个周末终于录了网络接口(CNI)第三方厂商中的佼佼者flannel和calico的实践!以及istio的实践!虽然都只是一部分,但是能迈出这一步,感觉已经是巨大的进步了,因为如果找借口可能天天都有借口,但是时间嘛,挤一挤总是有的!

Avatar

Aisen

Be water,my friend.