-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLRUCache.java
109 lines (93 loc) · 2.13 KB
/
LRUCache.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
import java.util.HashMap;
public class LRUCache {
public static void main(String[] args) {
LRU lru = new LRU(5);
lru.add(1);
lru.add(2);
lru.add(3);
lru.add(2);
lru.add(4);
lru.add(5);
lru.add(5);
lru.add(6);
lru.print();
}
}
class LRU {
HashMap<Integer, Node> map = new HashMap<>();
DoublyLinkList ll = new DoublyLinkList();
int capacity;
LRU(int capacity) {
this.capacity = capacity;
}
public void add(int data) {
if (map.containsKey(data)) {
if (ll.tailCheck(data)) {
return;
}
Node address = map.get(data);
ll.remove(address);
map.remove(data);
}
if (map.size() == capacity) {
int d = ll.removeFirst();
map.remove(d);
}
Node nn = ll.insert(data);
map.put(data, nn);
}
public void print() {
ll.print();
}
}
class DoublyLinkList {
Node head, tail;
public void remove(Node node) {
if (head == tail && head == node) {
head = tail = null;
} else if (head == node) {
head = head.next;
head.prev = null;
} else {
node.prev.next = node.next;
node.next.prev = node.prev;
}
}
public Node insert(int data) {
Node nn = new Node(data);
if (head == null) {
head = tail = nn;
} else {
nn.prev = tail;
tail.next = nn;
tail = nn;
}
return nn;
}
public int removeFirst() {
int data = head.data;
head = head.next;
return data;
}
public boolean tailCheck(int data) {
if (tail.data == data) {
return true;
}
return false;
}
public void print() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data + " ");
temp = temp.next;
}
}
}
class Node {
int data;
Node prev;
Node next;
Node(int data) {
this.data = data;
}
}