-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMRUCache.java
126 lines (91 loc) · 2.05 KB
/
MRUCache.java
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
import java.util.HashMap;
import java.util.Map;
/*
* Implementation by Eric Xing
* MRU cache data structure with LinkedHashMap and Doubly-Linked list
* Implements the CACHE interface
* O(1) add, O(1) query
*/
public class MRUCache implements Cache {
// doubly-linked node
static class Node {
int value;
Node prev;
Node next;
public Node(int value) {
this.value = value;
}
public Node() {
}
}
// Size variables
int count;
int capacity;
// LinkedList
Node head;
Node tail;
// HashMap for storing cache
Map<Integer, Node> cache = new HashMap<>();
// Constructor
public MRUCache(int capacity) {
// Initialize attributes
count = 0;
this.capacity = capacity;
head = new Node();
head.prev = null;
tail = new Node();
tail.next = null;
head.next = tail;
tail.prev = head;
}
// appends a new node at the tail of the LinkedList
void add_at_tail(Node node) {
node.next = tail;
node.prev = tail.prev;
tail.prev.next = node;
tail.prev = node;
}
/*
* removes a specific node by redirecting connections of the subsequent and
* previous nodes
*/
void remove(Node node) {
Node pre = node.prev;
Node next = node.next;
pre.next = next;
next.prev = pre;
}
// removes and returns the last node
Node pop() {
Node res = tail.prev;
remove(res);
return res;
}
// finds
public int get(int key) {
// use hashmap to get O(1) query
if (cache.containsKey(key)) {
Node node = cache.get(key);
remove(node);
add_at_tail(node);
return node.value;
}
// not found
return -1;
}
public void add(int value) {
// make a new node for the value
Node newNode = new Node(value);
// insert it into the HashMap
cache.put(value, newNode);
// Remove a value if neccesary to make space
if (count == capacity) {
Node tail = pop();
cache.remove(tail.value);
count--;
}
// Append it and update size accordingly
add_at_tail(newNode);
count++;
}
}