通过Golang的container/list实现LRU缓存算法

文章目录

    • 力扣:146. LRU 缓存
    • 主要结构 List 和 Element
      • 常用方法
      • 1. 初始化链表
      • 2. 插入元素
      • 3. 删除元素
      • 4. 遍历链表
      • 5. 获取链表长度
      • 使用场景
      • 注意事项
    • 源代码阅读

在 Go 语言中,container/list 包提供了一个双向链表的实现。链表是一种常见的数据结构,适用于频繁插入和删除操作的场景。container/list 包中的链表是双向的,意味着每个元素都包含指向前一个和后一个元素的指针。

力扣:146. LRU 缓存

力扣算法链接:https://leetcode.cn/problems/lru-cache/?envType=study-plan-v2&envId=top-100-liked

请你设计并实现一个满足 LRU (最近最少使用) 缓存 约束的数据结构。
实现 LRUCache 类:
LRUCache(int capacity) 以 正整数 作为容量 capacity 初始化 LRU 缓存。
int get(int key) 如果关键字 key 存在于缓存中,则返回关键字的值,否则返回 -1 。
void put(int key, int value) 如果关键字 key 已经存在,则变更其数据值 value ;如果不存在,则向缓存中插入该组 key-value 。如果插入操作导致关键字数量超过 capacity ,则应该 逐出 最久未使用的关键字。

函数 get 和 put 必须以 O(1) 的平均时间复杂度运行。

输入
[“LRUCache”, “put”, “put”, “get”, “put”, “get”, “put”, “get”, “get”, “get”]
[[2], [1, 1], [2, 2], [1], [3, 3], [2], [4, 4], [1], [3], [4]]

输出
[null, null, null, 1, null, -1, null, -1, 3, 4]

解释
LRUCache lRUCache = new LRUCache(2);
lRUCache.put(1, 1); // 缓存是 {1=1}
lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
lRUCache.get(1); // 返回 1
lRUCache.put(3, 3); // 该操作会使得关键字 2 作废,缓存是 {1=1, 3=3}
lRUCache.get(2); // 返回 -1 (未找到)
lRUCache.put(4, 4); // 该操作会使得关键字 1 作废,缓存是 {4=4, 3=3}
lRUCache.get(1); // 返回 -1 (未找到)
lRUCache.get(3); // 返回 3
lRUCache.get(4); // 返回 4

代码案例:

type Node struct {
	key   int
	value int
}

type LRUCache struct {
	capacity int
	list     *list.List
	mp       map[int]*list.Element
}

func Constructor(capacity int) LRUCache {
	return LRUCache{
		capacity: capacity,
		list:     list.New(),
		mp:       make(map[int]*list.Element),
	}
}

func (this *LRUCache) Get(key int) int {
	if v, ok := this.mp[key]; ok {
		this.list.MoveToFront(v)
		return v.Value.(*Node).value
	}
	return -1
}

func (this *LRUCache) Put(key int, value int) {
	if v, ok := this.mp[key]; ok {
		v.Value.(*Node).value = value
		this.list.MoveToFront(v)
        return
	}
	node := &Node{key, value}
	a := this.list.PushFront(node)
	this.mp[key] = a

	if this.list.Len() > this.capacity {
		tmp := this.list.Back()
		delete(this.mp, tmp.Value.(*Node).key)
		this.list.Remove(tmp)
	}
}

主要结构 List 和 Element

  • List: 表示一个双向链表。
type List struct {
	root Element // sentinel list element, only &root, root.prev, and root.next are used
	len  int     // current list length excluding (this) sentinel element
}
  • Element: 表示链表中的一个元素。
type Element struct {
	next, prev *Element
	list *List
	Value any
}

常用方法

1. 初始化链表

使用 list.New() 创建一个新的链表。

func main() {
	l := list.New()

	fmt.Printf("%+v\n",l)
}

在这里插入图片描述

2. 插入元素

  • PushBack(value interface{}) *Element: 在链表尾部插入一个元素。
  • PushFront(value interface{}) *Element: 在链表头部插入一个元素。
  • InsertBefore(value interface{}, mark *Element) *Element: 在指定元素前插入一个元素。
  • InsertAfter(value interface{}, mark *Element) *Element: 在指定元素后插入一个元素。
func main() {
	l := list.New()

	l.PushBack(123)
	l.PushBack("nihao")
	l.PushFront("你好")
	l.PushFront(3.1415926)

	// 遍历
	for e := l.Front(); e != nil; e = e.Next() {
		fmt.Printf("%+v\n", e)
	}
}

通过运行结果可以发现,list其实就是一个环形的双向链表。
在这里插入图片描述

3. 删除元素

  • Remove(e *Element) interface{}: 删除链表中的指定元素。
func main() {
	l := list.New()

	l.PushBack("nihao")

	a:=l.Remove(l.Back())
	fmt.Println(a)
}

在这里插入图片描述

4. 遍历链表

  • Front() *Element: 返回链表的第一个元素。
  • Back() *Element: 返回链表的最后一个元素。
  • Next() *Element: 返回当前元素的下一个元素。
  • Prev() *Element: 返回当前元素的前一个元素。
func main() {
    l := list.New()

    l.PushBack(1)
    l.PushBack(2)
    l.PushBack(3)

    // 从前往后遍历
    for e := l.Front(); e != nil; e = e.Next() {
        fmt.Println(e.Value)
    }

    // 从后往前遍历
    for e := l.Back(); e != nil; e = e.Prev() {
        fmt.Println(e.Value)
    }
}

5. 获取链表长度

  • Len() int: 返回链表中元素的个数。
func main() {
    l := list.New()

    l.PushBack(1)
    l.PushBack(2)
    l.PushBack(3)

    fmt.Println(l.Len()) // 输出: 3
}

使用场景

  • 频繁插入和删除: 链表在插入和删除操作上比数组更高效,尤其是在中间位置。
  • 实现队列和栈: 链表可以用来实现队列(FIFO)和栈(LIFO)等数据结构。
  • 动态数据存储: 当数据量不确定或需要动态调整时,链表是一个很好的选择。

注意事项

  • 内存开销: 链表的每个元素都需要额外的内存来存储前后指针,因此内存开销比数组大。
  • 随机访问性能差: 链表不支持随机访问,访问某个元素需要从头或尾开始遍历。

源代码阅读

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// Package list implements a doubly linked list.
//
// To iterate over a list (where l is a *List):
//
//	for e := l.Front(); e != nil; e = e.Next() {
//		// do something with e.Value
//	}
package list

// Element is an element of a linked list.
type Element struct {
	//双链表元素中的下一个和上一个指针。
	//为了简化实现,在内部实现了列表l
	//作为一个环,这样&l.root既是最后一个元素的下一个元素
	//list元素(l.Back())和第一个列表的前一个元素
	//元素(l.Front())。
	next, prev *Element

	// The list to which this element belongs.
	list *List

	// The value stored with this element.
	Value any
}

// Next returns the next list element or nil.
func (e *Element) Next() *Element {
	if p := e.next; e.list != nil && p != &e.list.root {
		return p
	}
	return nil
}

// Prev returns the previous list element or nil.
func (e *Element) Prev() *Element {
	if p := e.prev; e.list != nil && p != &e.list.root {
		return p
	}
	return nil
}

// List represents a doubly linked list.
// The zero value for List is an empty list ready to use.
type List struct {
	root Element // sentinel list element, only &root, root.prev, and root.next are used
	len  int     // current list length excluding (this) sentinel element
}

// Init initializes or clears list l.
func (l *List) Init() *List {
	l.root.next = &l.root
	l.root.prev = &l.root
	l.len = 0
	return l
}

// New returns an initialized list.
func New() *List { return new(List).Init() }

// Len returns the number of elements of list l.
// The complexity is O(1).
func (l *List) Len() int { return l.len }

// Front returns the first element of list l or nil if the list is empty.
func (l *List) Front() *Element {
	if l.len == 0 {
		return nil
	}
	return l.root.next
}

// Back returns the last element of list l or nil if the list is empty.
func (l *List) Back() *Element {
	if l.len == 0 {
		return nil
	}
	return l.root.prev
}

// lazyInit lazily initializes a zero List value.
func (l *List) lazyInit() {
	if l.root.next == nil {
		l.Init()
	}
}

// insert inserts e after at, increments l.len, and returns e.
func (l *List) insert(e, at *Element) *Element {
	e.prev = at
	e.next = at.next
	e.prev.next = e
	e.next.prev = e
	e.list = l
	l.len++
	return e
}

// insertValue is a convenience wrapper for insert(&Element{Value: v}, at).
func (l *List) insertValue(v any, at *Element) *Element {
	return l.insert(&Element{Value: v}, at)
}

// remove removes e from its list, decrements l.len
func (l *List) remove(e *Element) {
	e.prev.next = e.next
	e.next.prev = e.prev
	e.next = nil // avoid memory leaks
	e.prev = nil // avoid memory leaks
	e.list = nil
	l.len--
}

// move moves e to next to at.
func (l *List) move(e, at *Element) {
	if e == at {
		return
	}
	e.prev.next = e.next
	e.next.prev = e.prev

	e.prev = at
	e.next = at.next
	e.prev.next = e
	e.next.prev = e
}

// Remove removes e from l if e is an element of list l.
// It returns the element value e.Value.
// The element must not be nil.
func (l *List) Remove(e *Element) any {
	if e.list == l {
		// if e.list == l, l must have been initialized when e was inserted
		// in l or l == nil (e is a zero Element) and l.remove will crash
		l.remove(e)
	}
	return e.Value
}

// PushFront inserts a new element e with value v at the front of list l and returns e.
func (l *List) PushFront(v any) *Element {
	l.lazyInit()
	return l.insertValue(v, &l.root)
}

// PushBack inserts a new element e with value v at the back of list l and returns e.
func (l *List) PushBack(v any) *Element {
	l.lazyInit()
	return l.insertValue(v, l.root.prev)
}

// InsertBefore inserts a new element e with value v immediately before mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertBefore(v any, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	// see comment in List.Remove about initialization of l
	return l.insertValue(v, mark.prev)
}

// InsertAfter inserts a new element e with value v immediately after mark and returns e.
// If mark is not an element of l, the list is not modified.
// The mark must not be nil.
func (l *List) InsertAfter(v any, mark *Element) *Element {
	if mark.list != l {
		return nil
	}
	// see comment in List.Remove about initialization of l
	return l.insertValue(v, mark)
}

// MoveToFront moves element e to the front of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToFront(e *Element) {
	if e.list != l || l.root.next == e {
		return
	}
	// see comment in List.Remove about initialization of l
	l.move(e, &l.root)
}

// MoveToBack moves element e to the back of list l.
// If e is not an element of l, the list is not modified.
// The element must not be nil.
func (l *List) MoveToBack(e *Element) {
	if e.list != l || l.root.prev == e {
		return
	}
	// see comment in List.Remove about initialization of l
	l.move(e, l.root.prev)
}

// MoveBefore moves element e to its new position before mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveBefore(e, mark *Element) {
	if e.list != l || e == mark || mark.list != l {
		return
	}
	l.move(e, mark.prev)
}

// MoveAfter moves element e to its new position after mark.
// If e or mark is not an element of l, or e == mark, the list is not modified.
// The element and mark must not be nil.
func (l *List) MoveAfter(e, mark *Element) {
	if e.list != l || e == mark || mark.list != l {
		return
	}
	l.move(e, mark)
}

// PushBackList inserts a copy of another list at the back of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushBackList(other *List) {
	l.lazyInit()
	for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() {
		l.insertValue(e.Value, l.root.prev)
	}
}

// PushFrontList inserts a copy of another list at the front of list l.
// The lists l and other may be the same. They must not be nil.
func (l *List) PushFrontList(other *List) {
	l.lazyInit()
	for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() {
		l.insertValue(e.Value, &l.root)
	}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/983378.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

从零开始学机器学习——线性和多项式回归

首先给大家介绍一个很好用的学习地址:https://cloudstudio.net/columns 在之前的学习中,我们已经对数据的准备工作以及数据可视化有了一定的了解。今天,我们将深入探讨基本线性回归和多项式回归的概念与应用。 如果在过程中涉及到一些数学知…

【数据结构初阶第十八节】八大排序系列(上篇)—[详细动态图解+代码解析]

看似不起眼的日复一日,总会在某一天让你看到坚持的意义。​​​​​​云边有个稻草人-CSDN博客 hello,好久不见! 目录 一. 排序的概念及运用 1. 概念 2. 运用 3. 常见排序算法 二. 实现常见排序算法 1. 插入排序 (1&…

SPI驱动五) -- SPI_DAC上机实验(使用spidev)

文章目录 参考资料:一、DAC硬件1.1 原理图1.2 扩展板连接图1.3 DAC原理 二、编写APP三、编写设备树四、上机实验五、Bug分析六、总结 参考资料: 参考资料: 内核驱动:drivers\spi\spidev.c 内核提供的测试程序:tools\…

基于Asp.net的驾校管理系统

作者:计算机学姐 开发技术:SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等,“文末源码”。 专栏推荐:前后端分离项目源码、SpringBoot项目源码、Vue项目源码、SSM项目源码、微信小程序源码 精品专栏:…

Spring (八)AOP-切面编程的使用

目录 实现步骤&#xff1a; 1 导入AOP依赖 2 编写切面Aspect 3 编写通知方法 4 指定切入点表达式 5 测试AOP动态织入 图示&#xff1a; 实现步骤&#xff1a; 1 导入AOP依赖 <!-- Spring Boot AOP依赖 --><dependency><groupId>org.springframework.b…

阿里云CTF2025 ---Web

ezoj 啊&#xff1f;怎么整个五个算法题给CTF选手做&#xff1f;&#xff1f;这我不得不展示一下真正的技术把测评机打穿。 可以看到源码 import os import subprocess import uuid import json from flask import Flask, request, jsonify, send_file from pathlib import Pa…

WSL(ubunt)中使用ollama部署deepseek-7b

想在自己的Win11电脑上部署Linux的DeepSeek模型&#xff0c;但在网上一直没有找到合适的相应教程&#xff0c;自己查询各种网上资源&#xff0c;以及询问一些AI大模型后成功安装&#xff0c;并整理了以下步骤。仅作为个人学习笔记使用&#xff0c;由于本人对各方面知识掌握不足…

蓝桥杯国赛—路径之谜(dfs详细解法)

一.题目 二.dfs解法 使用dfs算法可以递归遍历所有可能路径&#xff0c;如果找到错误的路径就进行回溯&#xff0c;只有找到正确的路径才会输出 public class Main {static class pair{int x;int y;public pair(int x,int y){this.x x;this.y y;} }public static void bfs()…

Jenkins在Windows上的使用(二):自动拉取、打包、部署

&#xff08;一&#xff09;Jenkins全局配置 访问部署好的Jenkins服务器网址localhost:8080&#xff0c;完成默认插件的安装后&#xff0c;接下来将使用SSH登录远程主机以实现自动化部署。 1. 配置插件 选择dashboard->Manage Jenkins->plugins 安装下面两个插件  …

记录小白使用 Cursor 开发第一个微信小程序(一):注册账号及下载工具(250308)

文章目录 记录小白使用 Cursor 开发第一个微信小程序&#xff08;一&#xff09;&#xff1a;注册账号及下载工具&#xff08;250308&#xff09;一、微信小程序注册摘要1.1 注册流程要点 二、小程序发布流程三、下载工具 记录小白使用 Cursor 开发第一个微信小程序&#xff08…

蓝耘智算 + 通义万相 2.1:为 AIGC 装上 “智能翅膀”,翱翔创作新天空

1. 引言&#xff1a;AIGC 的崛起与挑战 在过去几年中&#xff0c;人工智能生成内容&#xff08;AIGC&#xff09;技术突飞猛进。AIGC 涉及了文本生成、图像创作、音乐创作、视频制作等多个领域&#xff0c;并逐渐渗透到日常生活的方方面面。传统的内容创作方式已经被许多人类创…

C/C++中使用CopyFile、CopyFileEx原理、用法、区别及分别在哪些场景使用

文章目录 1. CopyFile原理函数原型返回值用法示例适用场景 2. CopyFileEx原理函数原型返回值用法示例适用场景 3. 核心区别4. 选择建议5. 常见问题6.区别 在Windows系统编程中&#xff0c;CopyFile和CopyFileEx是用于文件复制的两个API函数。它们的核心区别在于功能扩展性和控制…

计算机性能指标(计网笔记)

计算机性能指标&#xff1a;速率、带宽、吞吐率、时延、时延带宽积、往返时间RTT、利用率 速率 数据的传输速率&#xff0c;单位bit/s&#xff0c;或kbit/s&#xff0c;Mbit/s&#xff0c;Gbit/s 4*10**10bit/s40Gbit/s 常用带宽单位&#xff1a; 千比每秒kb/s 兆比每秒Mb/s…

Python基于Django的医用耗材网上申领系统【附源码、文档说明】

博主介绍&#xff1a;✌Java老徐、7年大厂程序员经历。全网粉丝12w、csdn博客专家、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专栏推荐订阅&#x1f447;&…

php代码审计工具-rips

代码审计 代码审计就是检查所写的代码中是否有漏洞&#xff0c;检查程序的源代码是否有权限从而被黑客攻击&#xff0c;同时也检查了书写的代码是否规范。通过自动化的审查和人工审查的方式&#xff0c;逐行检查源代码&#xff0c;发现源代码中安全缺陷所造成的漏洞&#xff0…

工作学习笔记:HarmonyOS 核心术语速查表(v14 实战版)

作为在 HarmonyOS 开发一线摸爬滚打的工程师&#xff0c;笔者在 v14 版本迭代中整理了这份带血的实战术语表。 一、架构基础术语速查 A 系列术语 术语官方定义笔者解读&#xff08;v14 实战版&#xff09;开发陷阱 & 解决方案abc 文件ArkCompiler 生成的字节码文件打包时…

Trae IDE新建C#工程

目录 1 结论 2 项目结构 3 项目代码 1 结论 新建C#工程来说&#xff0c;Trae的Chat比DeepSeek的Coder好用。 2 项目结构 MyWinFormsApp/ │ ├── Program.cs ├── Form1.cs ├── Form1.Designer.cs ├── MyResources/ │ └── MyResources.resx └── MyWin…

大数据学习(55)-BI工具数据分析的使用

&&大数据学习&& &#x1f525;系列专栏&#xff1a; &#x1f451;哲学语录: 承认自己的无知&#xff0c;乃是开启智慧的大门 &#x1f496;如果觉得博主的文章还不错的话&#xff0c;请点赞&#x1f44d;收藏⭐️留言&#x1f4dd;支持一下博主哦&#x1f91…

Apache Kafka单节点极速部署指南:10分钟搭建开发单节点环境

Apache Kafka单节点极速部署指南&#xff1a;10分钟搭建开发单节点环境 Kafka简介&#xff1a; Apache Kafka是由LinkedIn开发并捐赠给Apache基金会的分布式流处理平台&#xff0c;现已成为实时数据管道和流应用领域的行业标准。它基于高吞吐、低延迟的设计理念&#xff0c;能够…

【干货教程】Windows电脑本地部署运行DeepSeek R1大模型(基于Ollama和Chatbox)

文章目录 一、环境准备二、安装Ollama2.1 访问Ollama官方网站2.2 下载适用于Windows的安装包2.3 安装Ollama安装包2.4 指定Ollama安装目录2.5 指定Ollama的大模型的存储目录 三、选择DeepSeek R1模型四、下载并运行DeepSeek R1模型五、常见问题解答六、使用Chatbox进行交互6.1 …