1
1
class LRUCache {
2
- unordered_map<int , int > hash;
3
- list<int > lru;
4
- int n;
5
- public:
6
- void findAndDelete (int key)
2
+
3
+ typedef struct node
7
4
{
8
- // Find the key in list and delete
9
- for (auto it = lru.begin (); it != lru.end (); ++it)
10
- {
11
- // cout <<*it<<"\n";
12
- if (*it==key)
13
- {
14
- lru.erase (it);
15
- break ;
16
- }
17
- }
5
+ int key;
6
+ int value;
7
+ struct node *prev;
8
+ struct node *next;
9
+ }N;
10
+ unordered_map<int , N*> hash;
11
+ N *pool;
12
+ N *front; // head of list
13
+ N *back;
14
+
15
+ void insert (N* node, int key, int value)
16
+ {
17
+ // Insert at front of link list
18
+ node->key = key;
19
+ node->value =value;
20
+ node->prev = NULL ;
21
+ node->next = front;
22
+ if (front)
23
+ front->prev = node;
24
+ front = node;
25
+ if (!back) // when list is empty
26
+ back = front;
27
+ hash[key] = node;// Insert in hash table
28
+ }
29
+ void update (N *n, int value)
30
+ {
31
+ n->value = value; // update the valie
32
+ if (n==front) // if update the front node, no processing required
33
+ return ;
34
+ // re-wire
35
+ if (n->prev )
36
+ n->prev ->next = n->next ;
37
+ if (n->next )
38
+ n->next ->prev = n->prev ;
39
+ else // Back pointer is updated when the back node is accessed
40
+ back = n->prev ;// update back pointer
41
+
42
+ // Move to top
43
+ n->next = front;
44
+ n->prev = NULL ;
45
+ front->prev = n;
46
+ front = n;
47
+ }
48
+ void remove ()
49
+ {
50
+ N * node = back->prev ;
51
+ if (node)
52
+ node->next = NULL ;
53
+ back = node;
18
54
}
55
+ int n;
56
+ int size;
57
+ public:
19
58
LRUCache (int capacity) {
20
59
n = capacity;
60
+ size = 0 ;
61
+ pool = new N[n];
62
+ front = back = NULL ;
21
63
}
22
64
23
65
int get (int key) {
@@ -26,35 +68,31 @@ class LRUCache {
26
68
return -1 ;
27
69
else
28
70
{
29
- findAndDelete (key);
30
- // and move to front
31
- lru.push_front (key);
32
-
33
- return hash[key];
71
+ update (hash[key], hash[key]->value );
72
+ return hash[key]->value ;
34
73
}
35
-
36
-
37
74
}
38
75
39
- void put (int key, int value) {
76
+ void put (int key, int value)
77
+ {
78
+ // cout<< value<<"\n";
79
+ N *node;
40
80
// If existing key is geting inserted
41
81
if (hash.find (key)!=hash.end ()) // key present
42
- findAndDelete (key);
43
-
44
- if (hash.find (key)==hash.end ())
82
+ update (hash[key], value);
83
+ else
45
84
{
46
85
if (hash.size ()==n)
47
86
{
48
- // Find tail item from LRU list.
49
- int indx = lru. back () ;
50
- lru. pop_back ();
51
- hash. erase (indx );
87
+
88
+ node = back;
89
+ hash. erase (back-> key ); // Remove the entry from hash table
90
+ remove ( ); // Remove the back node from LRU List
52
91
}
53
- }
54
-
92
+ else
93
+ node = &pool[size++];
55
94
56
- hash[key] = value;
57
- // insert in LRU List;
58
- lru.push_front (key);
95
+ insert (node, key, value);
96
+ }
59
97
}
60
98
};
0 commit comments