操操操

设计实现一个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)
	}
}
Avatar

Aisen

Be water,my friend.