雙向鏈表實現的簡易緩存(LRU Cache)

問題:

Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.

get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

解析:

實際上實現一個簡易的緩存,實現每次使用時將該值前置,緩存滿時先清除最不常用的部分。是大多數緩存基礎原理。使用雙向鏈表實現,每次操作後將操作節點置前,刪除時先刪除結尾點。

代碼:

struct LRUNode
{
	int key;
	int val;
	LRUNode *pre;
	LRUNode *next;
	LRUNode(int k, int v):key(k),val(v),pre(NULL),next(NULL){}
};
class LRUCache
{
	int m_capacity;
	int m_size;
	LRUNode *m_head, *m_end;
public:
	LRUCache(int capacity)
	{
		m_capacity = capacity;
		m_size = 0;
		m_head = NULL;
		m_end = NULL;
	}
private:
    void insert(int key, int val)
	{
		LRUNode *t = new LRUNode(key,val);
		if(m_head == NULL)
		{
			m_head = t;
		}
		else
		{
			if(m_end == NULL) m_end = m_head;
			t->next = m_head;
			m_head->pre = t;
			m_head = t;
		}
		m_size++;
	}
	void deleteLRUNode()
	{
		if(m_end == m_head || m_end == NULL) 
			m_end = m_head = NULL;
		else 
		{
			LRUNode *temp = m_end;
			m_end = m_end->pre;
			m_end->next = NULL;
			delete temp;
		}
		m_size--;
	}
	LRUNode * find( int key )
	{
		for(LRUNode *p = m_head; p != NULL; p = p->next)
		{
			if(p->key == key)
				return p;
		}
		return NULL;
	}
	void moveToHead(LRUNode *p)
	{
		if(p == m_head) return;
		if(p == m_end) m_end = p->pre;
		p->pre->next = p->next;
		if(p->next != NULL) p->next->pre = p->pre;
		p->next = m_head;
		m_head->pre = p;
		m_head = p;
	}
public:
	int get(int key)
	{
		LRUNode * p = find(key);
		if( p != NULL )
		{
			moveToHead(p);
			return p->val;
		}
		return -1;
	}
	void set(int key, int val)
	{
		if(m_capacity == 0) return;
		LRUNode * p = find(key);
		if(p == NULL)
		{
			if(m_size == m_capacity)
				deleteLRUNode();
			insert(key, val);
		}
		else
		{
			p->val = val;
			moveToHead(p);
		}
	}
};
分析:
真的不知道該寫什麼,代碼不是一次過的,主要是對head和end 的處理上需要注意。

還是給自己長經驗吧~

發佈了35 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章