漫画算法笔记
哈希链表
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <string>
#include <map>
using namespace std;
struct Node
{
Node(string key, string value)
:_key(key), _value(value) {};
Node * _pre = nullptr;
Node * _next = nullptr;
string _key;
string _value;
};
class LRUCache
{
public:
LRUCache(int limit)
{
_limit = limit;
}
~LRUCache()
{
Node *node = _head;
while (node->_next == nullptr)
{
Node *next = node->_next;
delete node;
node = next;
}
if(node)
delete node;
}
string get(string key)
{
auto iter = _map.find(key);
if (iter == _map.end())
{
return "";
}
string value = iter->second->_value;
refreshNode(iter->second);
return value;
}
void put(string key, string value)
{
auto iter = _map.find(key);
if(iter == _map.end())
{
if ((int)_map.size() >= _limit )
{
Node *delNode = _head;
string oldKey = removeNode(_head);
delete delNode;
_map.erase(oldKey);
}
Node *node = new Node(key, value);
addNode(node);
_map.insert(make_pair(key, node));
}
else
{
iter->second->_value = value;
refreshNode(iter->second);
}
}
void refreshNode(Node *node)
{
if (_end == nullptr)
{
return;
}
removeNode(node);
addNode(node);
}
string removeNode(Node *node)
{
if (node == _head && node == _end)
{
_head = nullptr;
_end = nullptr;
}
else if (node == _end)
{
_end = _end->_pre;
_end->_next = nullptr;
}
else if (node == _head)
{
_head = _head->_next;
_head->_pre = nullptr;
}
else
{
node->_pre->_next = node->_next;
node->_next->_pre = node->_pre;
}
return node->_key;
}
void addNode(Node *node)
{
if ( _end != nullptr )
{
_end->_next = node;
node->_pre = _end;
node->_next = nullptr;
}
_end = node;
if (_head == nullptr )
{
_head = node;
}
}
private:
Node *_head = nullptr;
Node *_end = nullptr;
int _limit;
map<string, Node*> _map;
};
int main(int argc, char** argv)
{
LRUCache lruCache(5);
lruCache.put("001", "用户1信息");
lruCache.put("002", "用户2信息");
lruCache.put("003", "用户3信息");
lruCache.put("004", "用户4信息");
lruCache.put("005", "用户5信息");
cout << lruCache.get("002") << endl;
lruCache.put("004", "更新用户4信息");
lruCache.put("006", "用户6信息");
cout << lruCache.get("001") << endl;
cout << lruCache.get("006") << endl;
system("pause");
return 0;
}