-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathLRU Cache.java
70 lines (66 loc) · 2.01 KB
/
LRU Cache.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
class LRUCache {
// Declare Node class for Doubly Linked List
class Node{
int key,value;// to store key and value
Node next,prev; // Next and Previous Pointers
Node(int k, int v){
key=k;
value=v;
}
}
Node head=new Node(-1,-1); // Default values
Node tail=new Node(-1,-1);
Map<Integer,Node>mp; // to store key and Node
int cap;
public LRUCache(int capacity) {
// initializing in constructor
cap=capacity;
head.next=tail;
tail.prev=head;
mp=new HashMap<Integer,Node>();
}
public int get(int key) {
// if map contains the specific key
if(mp.containsKey(key)){
Node existing=mp.get(key);
del(existing);
ins(existing);// reinserting to keep key after the head pointer and to update LRU list
return existing.value;
}
//otherwise
return -1;
}
public void put(int key, int value) {
// if map contains the key
if(mp.containsKey(key)){
Node existing=mp.get(key);
// remove from the map and delete from the LRU list
mp.remove(key);
del(existing);
}
// if map size is equal to spcified capacity of the LRU list
if(mp.size()==cap){
// remove from the map and delete from the LRU list
mp.remove(tail.prev.key);
del(tail.prev);
}
Node newNode = new Node(key,value);
ins(newNode);
mp.put(key,head.next);
}
public void ins(Node newNode){
//Insert always after the head of the linkedList
Node temp=head.next;
head.next=newNode;
newNode.prev=head;
newNode.next=temp;
temp.prev=newNode;
}
public void del(Node newNode){
//Remove the specified node using previous and next pointers
Node pr=newNode.prev;
Node nx=newNode.next;
pr.next=nx;
nx.prev=pr;
}
}