-
Notifications
You must be signed in to change notification settings - Fork 69
/
LRUCache.java
97 lines (82 loc) Β· 1.9 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
class Node{
int key;
int value;
Node next;
Node prev;
Node(int key,int value){
this.key=key;
this.value=value;
}
}
class LRUCache
{
static int capacity;
static HashMap<Integer,Node> mp;
static Node head;
static Node tail;
//Constructor for initializing the cache capacity with the given value.
LRUCache(int cap)
{
this.capacity=cap;
mp=new HashMap<>();
head=null;
tail=null;
}
static void shiftForward(Node node){
remove(node);
addForward(node);
}
static void remove(Node node){
Node prev=node.prev;
Node next=node.next;
if(prev!=null){
prev.next=next;
}else{
head=next;
}
if(next!=null){
next.prev=prev;
}else{
tail=prev;
}
}
static void addForward(Node node){
node.prev=null;
node.next=head;
if(head!=null){
head.prev=node;
}
head=node;
if(tail==null){
tail=node;
}
}
//Function to return value corresponding to the key.
public static int get(int key)
{
if(mp.containsKey(key)){
Node node=mp.get(key);
shiftForward(node);
return node.value;
}
return -1;
}
//Function for storing key-value pair.
public static void set(int key, int value)
{
// your code here
if(mp.containsKey(key)){
Node node=mp.get(key);
node.value=value;
shiftForward(node);
return;
}
Node temp=new Node(key,value);
if(mp.size()==capacity){
mp.remove(tail.key);
remove(tail);
}
addForward(temp);
mp.put(key,temp);
}
}