class LRUCache{ public: struct node { int key; int value; node(int k,int v):key(k),value(v){} }; LRUCache(int capacity1) { capacity = capacity1; } int get(int key) { unordered_map<int, node *>::iterator it = pos.find(key); if(it == pos.end()) return -1; node * check = it->second; int result = check->value; linked.remove(check); linked.push_front(check); } void set(int key, int value) { unordered_map<int, node *>::iterator it = pos.find(key); if(it != pos.end()) { node *t = it->second; t->value = value; linked.remove(t); linked.push_front(t); } else { node *t = new node(key, value); pos.insert(make_pair(key, t)); if(linked.size() < capacity) { linked.push_front(t); } else { node *temp = linked.back(); linked.pop_back(); linked.push_front(t); pos.erase(temp->key); delete temp; } } } private: int capacity; unordered_map<int, node *> pos; list<node *> linked; };
原文:http://www.cnblogs.com/ouchengeng/p/4135984.html