LRU缓存-力扣

struct LinkNode{
    int _key;
    int _value;
    LinkNode* prev;
    LinkNode* next;
    LinkNode() : _key(0), _value(0), prev(nullptr), next(nullptr) {}
    LinkNode(int key, int value): _key(key), _value(value), prev(nullptr), next(nullptr) {}
};
class LRUCache {
private:
    unordered_map<int, LinkNode*> cache;
    LinkNode* head;
    LinkNode* tail;
    int _size;
    int _capacity;

    void remove(LinkNode* x){
        x->prev->next = x->next;
        x->next->prev = x->prev;
    }
    void push_front(LinkNode* x){
        x->prev = head;
        x->next = head->next;
        head->next->prev = x;
        head->next = x;
    }
    LinkNode* get_node(int key){
        auto it = cache.find(key);
        if(it == cache.end()){
            return nullptr;
        }
        auto node = it->second;
        remove(node);
        push_front(node);
        return node;
    }
public:
    LRUCache(int capacity) {
        _capacity = capacity;
        _size = 0;
        head = new LinkNode();
        tail = new LinkNode();
        head->next = tail;
        tail->prev = head;  
    }
    
    int get(int key) {
        auto node = get_node(key);
        return node ? node->_value : -1;
    }
    
    void put(int key, int value) {
        auto node = get_node(key);
        if(node){
            node->_value = value;
            //push_front(node);
            return;
        }
        LinkNode* onenode = new LinkNode(key, value);
        cache.insert(make_pair(key, onenode));
        push_front(onenode);
        _size++;
        if(_size > _capacity){
            auto back_node = tail->prev;
            cache.erase(back_node->_key);
            _size--;
            remove(back_node);
            delete back_node;
        }
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值