-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLRU.cs
More file actions
48 lines (37 loc) · 1.13 KB
/
LRU.cs
File metadata and controls
48 lines (37 loc) · 1.13 KB
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
using System.Collections.Generic;
namespace AlgorithmsAndDataStructures.DataStructures.Cache;
public class Lru
{
private readonly int capacity;
private readonly CacheDoubleLinkedList list;
private readonly Dictionary<int, CacheEntry> values;
private int entriesCount;
public Lru(int capacity)
{
values = new Dictionary<int, CacheEntry>();
this.capacity = capacity;
entriesCount = 0;
list = new CacheDoubleLinkedList();
}
public void Add(int key, string value)
{
if (values.ContainsKey(key)) values[key].UpdateValue(value);
if (entriesCount == capacity)
{
var removedEntry = list.RemoveTail();
values.Remove(removedEntry.Key);
entriesCount--;
}
var newEntry = new CacheEntry(key, value);
list.InsertToHead(newEntry);
values.Add(key, newEntry);
entriesCount++;
}
public string Get(int key)
{
if (!values.ContainsKey(key)) return null;
var entry = values[key];
if (entriesCount > 1) list.MoveToHead(entry);
return entry.Value;
}
}