-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLRUCache.java
More file actions
76 lines (67 loc) · 1.85 KB
/
Copy pathLRUCache.java
File metadata and controls
76 lines (67 loc) · 1.85 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
76
import java.util.HashMap;
import java.util.Map;
class LRUCache {
class ListNode{
int key, value;
ListNode pre, next;
public ListNode(int key, int value) {
this.key = key;
this.value = value;
}
}
private ListNode head, tail;
private Map<Integer, ListNode> cache;
private int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
head = new ListNode(0, 0);
tail = new ListNode(0, 0);
head.next = tail;
tail.pre = head;
head.pre = null;
tail.next = null;
cache = new HashMap<>();
}
private void remove(ListNode node) {
node.pre.next = node.next;
node.next.pre = node.pre;
}
private void add(ListNode node) {
node.next = head.next;
node.pre = head;
node.next.pre = node;
head.next = node;
}
private void removeToHead(ListNode node) {
this.remove(node);
this.add(node);
}
private ListNode removeTail() {
ListNode deletedNode = tail.pre;
this.remove(deletedNode);
return deletedNode;
}
public int get(int key) {
if (!cache.containsKey(key)) {
return -1;
}
ListNode node = cache.get(key);
this.removeToHead(node);
return node.value;
}
public void put(int key, int value) {
if (cache.containsKey(key)) {
ListNode node = cache.get(key);
node.value = value;
this.removeToHead(node);
} else {
if (cache.size() == capacity) {
ListNode deletedNode = this.removeTail();
cache.remove(deletedNode.key);
}
ListNode newNode = new ListNode(key, value);
cache.put(key, newNode);
this.add(newNode);
}
}
}