template <typename K, typename V>
class Node
{
public:
K key;
V value;
Node<K, V>* next;
Node<K, V>* last;
Node() = default;
Node(K k, V v)
{
key = k;
value = v;
next = NULL;
last = NULL;
}
};
template <class K, class V>
class List
{
public:
Node<K, V>* head;
Node<K, V>* end;
void addNode(Node<K, V>* node)
{
if (!node)
return;
if (!head)
{
head = node;
end = node;
}
else
{
end->next = node;
node->last = end;
end = node;
}
}
void removehead()
{
if (!head)
return;
Node<K, V>* temp = head;
head = head->next;
delete temp;
}
void moveToend(Node<K, V>* node)
{
if (!node || node == end)
return;
if (node == head)
node->next->last = NULL;
else
{
node->last->next = node->next;
node->next->last = node->last;
}
node->last = end;
node->next = NULL;
end->next = node;
end = node;
}
~List()
{
while (end)
{
Node<K, V>* temp = head;
head = head->next;
delete temp;
}
}
};
template<class K, class V>
class LRU
{
public:
List<K, V> L;//只有双端队列可以实现优先级更新,单链表不得行
hash_map<K, Node<K, V>*> map;//利用hash表实现随机存取
int Size;
LRU() = default;
LRU(int size)
{
Size = size;
}
void set(K key, V value)
{
if (map.find(key) == map.end())
{
Node<K, V>* node = new Node<K, V>(key, value);
map.insert({ key, node });
L.addNode(node);//更新hash表的同时,更新双端队列
if (map.size() > Size)//元素数量超过空间限制时删除LRU元素
{
map.erase(L.head->key);
L.removehead();
}
}
else
{
map[key]->value = value;
L.moveToend(map[key]);//更新优先级
}
}
V get(K key)
{
if (map.find(key) == map.end())
return NULL;
L.moveToend(map[key]);//更新优先级
return map[key]->value;
}
};