-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
75 lines (65 loc) · 1.73 KB
/
LRUCache.java
File metadata and controls
75 lines (65 loc) · 1.73 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
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
class LRUCache {
Map<Integer,Node> cache;
int capacity;
Node head;
Node tail;
int count;
public LRUCache(int capacity) {
this.cache = new HashMap<>();
this.capacity = capacity;
this.head = new Node(0,0);
this.tail = new Node(0,0);
this.head.next = tail;
this.tail.prev = head;
}
public int get(int key) {
Node node = cache.get(key);
if(node != null){
deleteNode(node);
addToHead(node);
return node.value;
}
return -1;
}
public void put(int key, int value) {
Node node = cache.get(key);
if(node == null){
// Create
Node newNode = new Node(key, value);
cache.put(newNode.key, newNode);
if(count<capacity){
count++;
addToHead(newNode);
}else{
cache.remove(tail.prev.key);
deleteNode(tail.prev);
addToHead(newNode);
}
}else{
// Update
deleteNode(node);
node.value = value;
addToHead(node);
}
}
private void addToHead(Node node){
node.next = head.next;
head.next.prev = node;
head.next = node;
node.prev = head;
}
private void deleteNode(Node node){
node.prev.next = node.next;
node.next.prev = node.prev;
}
private class Node{
int key;
int value;
Node prev;
Node next;
Node(int k, int v){
this.key = k;
this.value = v;
}
}
}