LRU cache的简单实现

从昨天想起这个东西,中午写好了,但是leetcode上还木有ac:

就是用双链表存储,同时用一个map存储链表:

		LRUCache(int capacity):
			maxSize(capacity)
			, curSize(0){
				pHead = new LinkedList(-1, -1);
				pHead->pre = pHead;
				pHead->next = pHead;
			}
			
		~LRUCache(){
			for (MapList::iterator iter = mapList.begin(); iter != mapList.end(); ++iter){
				delete iter->second;
			}
			delete pHead;
		}
			
		void set(int key,int val){
			MapList::iterator iter = mapList.find(key);
			if (mapList.end() == iter){
				if (maxSize == curSize){
					LinkedList* pToDel = pHead->pre;
					pHead->pre = pToDel->pre;
					pToDel->pre->next = pHead;
					
					mapList.erase(pToDel->key);
					
					pToDel->key = key;
					pToDel->val = val;
					
					mapList[key] = pToDel; 
				}
				else{
					LinkedList* pCurList = new LinkedList(key, val);
					
					pHead->next->pre = pCurList;
					pCurList->next = pHead->next;
					pHead->next = pCurList;
					pCurList->pre = pHead;
					
					mapList[key] = pCurList;
					
					++curSize;
				}
			}
			else{
				LinkedList* pCurList = iter->second;
				pCurList->pre->next = pCurList->next;
				pCurList->next->pre = pCurList->pre;
				
				pCurList->next = pHead->next;
				pCurList->pre = pHead;
				pHead->next = pCurList;
			}
		}
		
		int get(int key){
			MapList::iterator iter = mapList.find(key);
			if (mapList.end() == iter){
				printf("can't find key:%d\n", key);
				return -1;
			}
			else{
				LinkedList* pCurList = iter->second;
				pCurList->pre->next = pCurList->next;
				pCurList->next->pre = pCurList->pre;
				
				pCurList->next = pHead->next;
				pCurList->pre = pHead;
				pHead->next = pCurList;
			}
			
			return (iter->second)->val;
		}
	private:
		struct LinkedList{
			int key;
			int val;
			LinkedList* pre;
			LinkedList* next;
			LinkedList(int key, int val):
				key(key)
				, val(val)
				, pre(NULL)
				, next(NULL){
				}
		};
		const int maxSize;
		int curSize;
		LinkedList* pHead;
		typedef std::map MapList;
		MapList mapList;



这里实现的思路是set时超过了size就删掉最早插入的那个节点。

貌似木有用到get这个查询的用法,想了下还是保存查询的次数纪录,可以用位图的办法。下午吃饭的时候再写。

你可能感兴趣的:(算法学习)