左神算法学习日记——LRU数据结构设计

template 
class Node
{
public:
	K key;
	V value;
	Node* next;
	Node* last;
	Node() = default;
	Node(K k, V v)
	{
		key = k;
		value = v;
		next = NULL;
		last = NULL;
	}
};

template 
class List
{
public:
	Node* head;
	Node* end;
	void addNode(Node* 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* temp = head;
		head = head->next;
		delete temp;
	}
	void moveToend(Node* 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* temp = head;
			head = head->next;
			delete temp;
		}
	}
};

template
class LRU
{
public:
	List L;//只有双端队列可以实现优先级更新,单链表不得行
	hash_map*> map;//利用hash表实现随机存取
	int Size;
	LRU() = default;
	LRU(int size)
	{
		Size = size;
	}
	void set(K key, V value)
	{
		if (map.find(key) == map.end())
		{
			Node* node = new Node(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;
	}
};

 

你可能感兴趣的:(学习日记)