-
Notifications
You must be signed in to change notification settings - Fork 1
/
lru_cache.cpp
77 lines (69 loc) · 1.22 KB
/
lru_cache.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "lru_cache.h"
int LRUCache::get(int key)
{
if(cache.find(key) != cache.end())
{
Node *node = cache[key];
moveToFront(node);
return node->value;
}
return -1;
}
void LRUCache::put(int key, int value)
{
if(cache.find(key) != cache.end())
{
Node *node = cache[key];
node->value = value;
moveToFront(node);
return;
}
Node *node = new Node(key, value);
if(cache.size() == capacity)
{
cache.erase(tail->key);
removeNode(tail);
}
cache[key] = node;
addFirst(node);
}
void LRUCache::moveToFront(Node *node)
{
removeNode(node);
addFirst(node);
}
void LRUCache::removeNode(Node *node)
{
Node *prevNode = node->prev;
Node *nextNode = node->next;
if(prevNode != NULL)
{
prevNode->next = nextNode;
}
else
{
head = nextNode;
}
if(nextNode != NULL)
{
nextNode->prev = prevNode;
}
else
{
tail = prevNode;
}
}
void LRUCache::addFirst(Node *node)
{
node->next = head;
node->prev = NULL;
if(head != NULL)
{
head->prev = node;
}
head = node;
if(tail == NULL)
{
tail = node;
}
}