Design a data structure for the least recently used (LRU) cache strategy. It should support the following operations: get data and write data. get(key) Get data: if the key exists in the cache
Idea: The latest data is placed at the head of the linked list, if the size exceeds the size, the tail data is deleted.
struct Node
{ Node() { key = -1; value = 0; next = nullptr; pre = nullptr;//Easy to delete }
int value;
int key;
Node* next;
Node* pre;
};
class LRUCache {
public:
/*
* @param capacity: An integer
*/LRUCache(int capacity)
{
// do intialization if necessary
size_ = capacity;
head_ = nullptr;
tail_ = nullptr;
}
/*
* @param key: An integer
* @return: An integer
*/
int get(int key) {
// write your code here
auto it = cacheMap_.find(key);
if (it != cacheMap_.end())
{
moveNodeToHead(it->first);
return it->second->value;
}
return -1;
}
/*
* @param key: An integer
* @param value: An integer
* @return: nothing
*/
void set(int key, int value) {
// write your code here
auto it = cacheMap_.find(key);
if (it != cacheMap_.end())
{
it->second->value = value;
moveNodeToHead(key);
}
else
{
if (cacheMap_.size() == size_)
{
deleteTail();
}
if (cacheMap_.size() == 0)
{
Node*cur = new Node();
cur->value = value;
cur->key = key;
head_ = cur;
tail_ = cur;
cacheMap_[key] = cur;
return;
}
Node*cur = new Node();
cur->value = value;
cur->key = key;
//insert head
cur->next = head_;
head_->pre = cur;
head_ = cur;
cacheMap_ [key] = cur;
}
}
void moveNodeToHead(int key)
{
std::unordered_map<int, Node*> ::iterator it = cacheMap_.find(key);
Node* cur = it->second;
if (head_ == cur)//head
{
return;
}
if (tail_ == cur) //tail
{
tail_ = cur->pre;
tail_->next = nullptr;
cur->next = head_;
head_->pre = cur;
cur->pre = nullptr;
head_ = cur;
return;
}
// mid
cur->pre->next = cur->next;
cur->next->pre = cur->pre;
cur->next = head_;
head_->pre = cur;
cur->pre = nullptr;
head_ = cur;
}
void deleteTail()
{
int key = -1;
if (nullptr == tail_)
{
return;
}
Node* cur = tail_;
if ( tail_ == head_) //only one node
{
key = cur->key;
cacheMap_.erase(key);
delete cur;
head_ = nullptr;
tail_ = nullptr;
return;
}
tail_ = cur->pre;
key = cur->key;
tail_->next = nullptr;
cacheMap_.erase(key);
delete cur;
cur = nullptr;
}
private:
std::unordered_map<int, Node*>cacheMap_;
Node* head_;
Node* tail_;
int size_;
};
void test()
{
LRUCache cache(2);
cache.set(2,1);
cache.set(1, 1);
int a = cache.get(2);
cache.set(4, 1);
int b = cache.get(1);
b = cache.get(2);
/*LRUCache cache(1);
cache.set(2, 1);
int a = cache.get(2);
cache.set(3, 2);
int b = cache.get(2);
b = cache.get(3);*/
}
int main()
{
test();
getchar();
return 0;
}