kotlin实现LRUCache

与一般的结构不同,参考了LinkedHashMap,将经常访问的放在最后,linkedLast()

相关题目,https://leetcode.cn/problems/lru-cache/

kotlin 复制代码
class MyLRUCache(private val maxSize: Int) {
    class Node(
        val key: Int, var value: Int, var before: Node? = null, var after: Node? = null
    )

    private var head: Node? = null
    private var tail: Node? = null
    private val map = HashMap<Int, Node>()

    fun getAndPrintln(key: Int) = get(key).also {
        println("get ${key}, ${this}")
    }

    private fun linkLast(n: Node) {
        if (tail == null) {
            head = n
            tail = head
            return
        }
        tail!!.after = n
        n.before = tail
        tail = n
    }

    private fun removeFirst() {
        if (head == null) {
            return
        }
        head = head!!.after
        head!!.before = null
    }

    private fun linkRemove(n: Node) {
        if (n == head) {
            head = head!!.after
        }
        if (n == tail) {
            tail = tail!!.before
        }
        n.before?.after = n.after
        n.after?.before = n.before
        n.before = null
        n.after = null
    }

    fun putAndPritln(key: Int, value: Int) = put(key, value).also {
        println("put ${key},${value}, ${this}")
    }

    fun put(key: Int, value: Int) {
        // 存在
        if (key in map) {
            val n = map[key]!!
            n.value = value
            if (n == tail) {
                return
            }
            linkRemove(n)
            linkLast(n)
            return
        }
        // 新建
        val n = Node(key, value)
        map[key] = n
        linkLast(n)
        if (map.size > maxSize) {
            map -= head!!.key
            removeFirst()
        }
    }

    fun remove(key: Int): Int {
        // 不存在
        if (key !in map) {
            return -1
        }
        val n = map.remove(key)!!
        linkRemove(n)
        return n.value
    }

    fun get(key: Int): Int {
        if (key !in map) {
            return -1
        }
        val n = map[key]!!
        linkRemove(n)
        linkLast(n)
        return n.value
    }

    override fun toString() = StringBuilder().apply {
        append("[")
        var n = head
        while (n != null) {
            append(
                if (n == head) "" else ", "
            )
            append("${n.key}=${n.value}")
            n = n.after
        }
        append("]")
    }.toString()
}
相关推荐
Kapaseker1 小时前
Kotlin 老手怎么写代码?
android·kotlin
扛麻袋的少年15 小时前
7.Kotlin的日期类
开发语言·微信·kotlin
UserNamezhangxi1 天前
kotlin 协程笔记
java·笔记·kotlin·协程
曲莫终1 天前
正则表达式删除注释和多余换航
java·kotlin
叽哥1 天前
Kotlin学习第 2 课:Kotlin 基础语法:掌握变量、数据类型与运算符
android·kotlin·app
alexhilton1 天前
玩转Shader之学会如何变形画布
android·kotlin·android jetpack
zhangphil2 天前
Android Coil 3拦截器Interceptor计算单次请求耗时,Kotlin
android·kotlin
wayne2142 天前
Kotlin 空安全完整指南:彻底告别NullPointerException
kotlin
深盾科技3 天前
Kotlin Data Classes 快速上手
android·开发语言·kotlin
一条上岸小咸鱼3 天前
Kotlin 基本数据类型(五):Array
android·前端·kotlin