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()
}
相关推荐
雨白11 小时前
高阶函数的应用:简化 SharedPreferences 与 ContentValues 操作
kotlin
移动开发者1号12 小时前
Retrofit动态URL与Path参数处理
android·kotlin
移动开发者1号12 小时前
Android 中 OkHttp 的自定义 Interceptor 实现统一请求头添加
android·kotlin
小金子同志17 小时前
发现 Kotlin MultiPlatform 的一点小变化
kotlin
androidwork18 小时前
嵌套滚动交互处理总结
android·java·kotlin
橙子1991101621 小时前
Kotlin 中的 Object
android·开发语言·kotlin
岸芷漫步2 天前
Kotlin中协程的关键函数分析
kotlin
纳于大麓2 天前
Kotlin基础语法五
android·开发语言·kotlin
移动开发者1号2 天前
嵌套滚动交互处理总结
android·kotlin
移动开发者1号2 天前
Android工程中FTP加密传输与非加密传输的深度解析
android·java·kotlin