只考虑了LRU算法的获取数据和存放数据方法,学习了以下链接文章,个人用C++语言写了一遍。
另外涉及了内存操作,建议实现个人定义的拷贝和拷贝赋值方法,避免浅拷贝。
http://flychao88.iteye.com/blog/1977653
#include <list>
#include <iostream>
using namespace std;
class node
{
public:
node(node *p = NULL, node *n = NULL, int v = 0) : prev(p), next(n), value(v)
{
}
node(int v) : prev(NULL), next(NULL), value(v)
{
}
~node()
{
prev = NULL;
next = NULL;
}
node* prev;
node* next;
int value;
};
class lru
{
public:
lru(int size = 5): cacheSize(size), currentSize(0), head(NULL), tail(NULL)
{
}
~lru()
{
node* p = head;
node* temp = NULL;
while (p != NULL)
{
temp = head->next;
delete p;
p = temp;
}
head = NULL;
tail = NULL;
}
int getValue(int key)
{
node *curr = head;
while (NULL != curr)
{
if (curr->value == key)
{
moveToHead(curr);
return curr->value;
}
else
{
curr = curr->next;
}
}
return -1;
}
void putValue(int key)
{
if (-1 == getValue(key))
{
if (currentSize >= cacheSize)
{
node *temp = tail; //更新指针
tail = tail->prev;
tail->next = NULL;
temp->next = head;
head->prev = temp;
head = temp;
head->prev = NULL;
head->value = key; // 更新数据
}
else
{
currentSize++;
if (head == NULL)
{
head = new node(key);
tail = head;
}
else
{
node* temp = new node(key);
head->prev = temp;
temp->next = head;
head = temp;
}
}
}
}
private:
void moveToHead(node* curr)
{
if (curr == head)
{
return;
}
if (curr->prev != NULL)
{
curr->prev->next = curr->next;
}
if (curr->next != NULL)
{
curr->next->prev = curr->prev;
}
if (tail == curr)
{
tail = curr->prev;
}
if (NULL != head)
{
curr->next = head;
head->prev = curr;
head = curr;
head->prev = NULL;
}
}
private:
int cacheSize;
int currentSize;
node* head;
node* tail;
};
int main()
{
lru test(5);
test.putValue(0);
test.putValue(1);
test.putValue(2);
test.putValue(3);
test.putValue(4);
cout << test.getValue(0) << endl;
cout << test.getValue(1) << endl;
cout << test.getValue(2) << endl;
cout << test.getValue(3) << endl;
cout << test.getValue(4) << endl;
test.putValue(5);
test.putValue(6);
cout << test.getValue(0) << endl;
cout << test.getValue(1) << endl;
cout << test.getValue(2) << endl;
cout << test.getValue(3) << endl;
cout << test.getValue(4) << endl;
cout << test.getValue(5) << endl;
cout << test.getValue(6) << endl;
return 0;
}