这一篇实现主要实现了最近最少使用算法
#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;
}
如有侵权,请联系删除,如有错误,欢迎大家指正,谢谢