LRU Cache

/*
 * Solution.cpp
 *
 *  Created on: 2014年4月8日
 *      Author: William
 */

#include <iostream>
#include <map>
using namespace std;

struct Node {
	int key;
	int val;
	Node *prev;
	Node *next;
	Node(int k, int v) :
			key(k), val(v), prev(NULL), next(NULL) {
	}
};

class LRUCache {
public:
	int cap;
	int cnt;
	map<int, Node*> mp;
	Node *head, *tail;

	LRUCache(int capacity) {
		if (capacity < 1) return;
		cap = capacity;
		cnt = 0;
		mp.clear();
		head = new Node(-1, -1);
		tail = new Node(-1, -1);
		head->next = tail;
		tail->prev = head;
	}

	void putToHead(Node *p) {
		p->next = head->next;
		p->prev = head;
		p->next->prev = p;
		head->next = p;
	}

	int get(int key) {
		map<int, Node*>::iterator it = mp.find(key);
		if (it != mp.end()) {
			Node *p = it->second;
			p->prev->next = p->next;
			p->next->prev = p->prev;
			putToHead(p);
			return p->val;
		} else {
			return -1;
		}
	}

	void set(int key, int value) {
		if (cap < 1) return;
		map<int, Node*>::iterator it = mp.find(key);
		if (it != mp.end()) {
			Node *p = it->second;
			p->prev->next = p->next;
			p->next->prev = p->prev;
			putToHead(p);
			p->val = value;
		} else {
			Node *p = new Node(key, value);
			mp.insert(pair<int, Node*>(key, p));
			putToHead(p);
			cnt++;
			if (cnt > cap) {
				p = tail->prev;
				p->prev->next = tail;
				tail->prev = p->prev;
				mp.erase(p->key);
				delete p;
				cnt--;
			}
		}
	}
};

//int main() {
//	return 0;
//}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值