LRU算法实现

这一篇实现主要实现了最近最少使用算法

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

struct Node {
	int val;
	Node* last;
	Node* next;
	Node(int value) 
		: val(value), last(nullptr), next(nullptr)
	{ }
};

class DoubleLinkedList {
public:
	DoubleLinkedList() 
		: head(nullptr), tail(nullptr)
	{ }

	/* 最新加入的放在尾部 */
	void addNode(Node* node) {
		if (node == nullptr) {
			return;
		}
		if (head == nullptr || tail == nullptr) {
			head = tail = node;
		}
		else {
			tail->next = node;
			node->last = tail;
			tail = node;
		}
	}

	/* 将被访问过的放在尾部 */
	void moveNodeToTail(Node* node) {
		if (node == nullptr || node == tail) {
			return;
		}
		if (node == head) {
			head = head->next;
			head->last = nullptr;
		}
		else {
			node->last->next = node->next;
			node->next->last = node->last;
		}
		node->next = nullptr;
		node->last = tail;
		tail->next = node;
		tail = node;
	}

	void removeHeadNode() {
		if (head == nullptr) {
			return;
		}
		Node* res = head;
		if (head == tail) {
			head = tail = nullptr;
		}
		else {
			head = head->next;
			head->last = nullptr;
		}
		delete res;
	}

	~DoubleLinkedList() {
		while (head != nullptr) {
			tail = head;
			head = head->next;
			delete tail;
		}
	}

private:
	Node* head;
	Node* tail;
};

class LRUCache {
public:
	LRUCache(unsigned int capacity)
		: capacity(capacity) {
		/* 容量不能小于1 */
		if (capacity == 0) {
			throw string("The capacity has to be greater than zero!");
		}
	}

	int get(string key) {
		if (keyNodeMap.count(key)) {
			Node* node = keyNodeMap.at(key);
			doubleLinkedList.moveNodeToTail(node);
			return node->val;
		}
		return INT_MIN;
	}

	void set(string key, int value) {
		if (keyNodeMap.count(key)) {
			Node* node = keyNodeMap.at(key);
			node->val = value;
			doubleLinkedList.moveNodeToTail(node);
		}
		else {
			Node* node = new Node(value);
			keyNodeMap.insert(pair<string, Node*>(key, node));
			doubleLinkedList.addNode(node);
			if (keyNodeMap.size() > capacity) {
				doubleLinkedList.removeHeadNode();
			}
		}
	}

private:
	unordered_map<string, Node*> keyNodeMap;
	DoubleLinkedList doubleLinkedList;
	unsigned int capacity;
};

int main() {
	LRUCache lRuCache(3);
	lRuCache.set(string("A"), 1);
	lRuCache.set(string("B"), 2);
	lRuCache.set(string("C"), 3);
	int val = lRuCache.get(string("A"));
	lRuCache.set("D", 4);
	system("pause");
	return 0;
}

如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值