LRU 实现的四种方式

本文介绍了LRU缓存淘汰策略的四种实现方式,包括单链表、双向链表、unordered_map结合双向链表以及unordered_map结合list。各实现的函数时间复杂度均为O(1),能有效提高缓存操作效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LRU 实现的四种方式

单链表

class LRUCache {
   
private:
    struct Node {
   
        int key;
        int val;
        Node *next;

        Node(int key, int val) : key(key), val(val), next(nullptr) {
   }
    };

private:
    int capacity;
    Node *pHead;
public:
    LRUCache(int capacity) {
   
        this->capacity = capacity;
        // the size of list is key in head node
        pHead = new Node(0, 0);
    }

    int get(int key) {
   
        Node *pNode = pHead;
        while (nullptr != pNode->next) {
   
            if (key == pNode->next->key) {
   
                // found
                auto tmp = pNode->next;
                pNode->next = pNode->next->next;
                tmp->next = pHead->next;
                pHead->next = tmp;

                return pHead->next->val;
            }
            pNode = pNode->next;
        }
        // not found
        return -1;
    }

    void put(int key, int value) {
   
        Node *pNode = pHead;

        while (nullptr != pNode->next) {
   
            if (key == pNode->next->key) {
   
                pNode->next->val = value;
                auto tmp = pNode->next;
                pNode->next = pNode->next->next;
                tmp->next = pHead->next;
                pHead->next = tmp;
                return;
            }
            pNode = pNode->next;
        }
        // not found
        pNode = new Node(key, value);
        pNode->next = pHead->next;
        pHead->next = pNode;
        pHead->key++;
        if (pHead->key > capacity) {
   
            // remove last node
            pNode = pHead;
            while (nullptr != pNode->next && nullptr != pNode->next->next) {
   
                pNode = pNode->next;
            }
            auto last = pNode->next;
            pNode->next = nullptr;
            if (nullptr != last) {
   
                delete last;
                last == null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值