LRU C++实现记录

LRU实现记录

#include<iostream>
#include<unordered_map>
using namespace std;

class LRUCache {
private:
	struct node {
		int key;
		int value;
		node* left;
		node* right;
		node(int x, int y) :key(x), value(y), left(nullptr), right(nullptr) {}
	};
	int cap;
	node* head = nullptr;
	node* tail = nullptr;
	unordered_map<int, node*>umap;
public:
	//首先需要给出LRU的容量
	LRUCache(int capacity) {
		cap = capacity;
		//先给出头尾
		head = new node(0, 0);
		tail = new node(0, 0);
		head->right = tail;
		tail->left = head;
	}
	~LRUCache() {
		node* cur = head;
		while (cur != nullptr) {
			node* tmp = cur;
			cur = cur->right;
			delete tmp;
		}
	}
	void push_list(node* n) {
		n->left = head;
		n->right = head->right;
		head->right = n;
		n->right->left = n;
	}
	void pop_list(node* n) {
		//只是从双向链表中取出,未做其他操作
		n->left->right = n->right;
		n->right->left = n->left;
	}
	void put(int key, int value) {
		//如果本来有就更新值,如果没有就添加,超过就把最旧的删掉
		if (umap.count(key) == 0) {
			node* newnode = new node(key, value);
			push_list(newnode);
			umap[key] = newnode;
			if (umap.size() > cap) {
				node* drop = tail->left;
				umap.erase(drop->key);//注意操作时需要对链表操作和哈希表操作
				pop_list(drop);
				delete drop;
			}
		}
		else {
			umap[key]->value = value;
			pop_list(umap[key]);
			push_list(umap[key]);
		}

	}
	int get(int key) {
		if (umap.count(key) != 0) {
			pop_list(umap[key]);
			push_list(umap[key]);
			cout << umap[key]->value << endl;
			return umap[key]->value;
		}
		else {//找不到需要返回-1
			cout << "找不到" << endl;
			return -1;
		}
	}
};

int main() {
	LRUCache* cache = new LRUCache(2);
	cache->put(1, 1);
	cache->put(2, 2);
	cache->get(1);       // 返回  1
	cache->put(3, 3);    // 该操作会使得密钥 2 作废
	cache->get(2);       // 返回 -1 (未找到)
	cache->put(4, 4);    // 该操作会使得密钥 1 作废
	cache->get(1);       // 返回 -1 (未找到)
	cache->get(3);       // 返回  3
	cache->get(4);       // 返回  4
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值