Repository navigation
Expand file tree
/
Copy pathLRUCache.java
More file actions
131 lines (121 loc) · 3.19 KB
/
Copy pathLRUCache.java
File metadata and controls
131 lines (121 loc) · 3.19 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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package com.interview.linklist;
import java.util.HashMap;
import java.util.Map;
/**
* http://www.geeksforgeeks.org/implement-lru-cache/
* Test cases:
* MAX_SIZE greater than 1
* Delete when empty
* Delete when full
* Enter data more than max
* Delete till cache is empty
*/
public class LRUCache {
private Node head;
private Node tail;
private Map<Integer,Node> map = new HashMap<Integer,Node>();
private int MAX_SIZE = 5;
private int size = 0;
public LRUCache(int size){
MAX_SIZE = size;
}
public void used(int data){
if(containsInCache(data)){
Node node = map.get(data);
if(node != head){
deleteFromCache(data);
node.next = head;
head.before = node;
head = node;
map.put(data, node);
}
}else{
addIntoCache(data);
}
}
public void addIntoCache(int data){
size++;
if(head == null){
head = Node.newNode(data);
tail = head;
return;
}
if(size > MAX_SIZE){
tail = tail.before;
Node next = tail.next;
tail.next = null;
next.before = null;
map.remove(next.data);
}
Node newNode = Node.newNode(data);
newNode.next = head;
if(head != null){
head.before = newNode;
}
head = newNode;
map.put(data, newNode);
return;
}
public void printCache(){
Node temp = head;
while(temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public boolean containsInCache(int data)
{
return map.containsKey(data);
}
public void deleteFromCache(int data){
Node node = map.get(data);
if(node == null){
return;
}
map.remove(data);
if(size == 1){
head = null;
tail = null;
}
else if(node == head){
head = head.next;
if(head != null){
head.before = null;
}
node.next = null;
}else if(node == tail){
tail = tail.before;
tail.next = null;
}else{
Node before = node.before;
Node next = node.next;
before.next = next;
next.before = before;
}
}
public static void main(String args[]){
LRUCache lruCache = new LRUCache(5);
lruCache.used(4);
lruCache.used(5);
lruCache.printCache();
lruCache.used(6);
lruCache.printCache();
lruCache.used(5);
lruCache.printCache();
lruCache.used(9);
lruCache.printCache();
lruCache.used(10);
lruCache.printCache();
lruCache.used(11);
lruCache.printCache();
lruCache.used(16);
lruCache.printCache();
lruCache.used(10);
lruCache.printCache();
lruCache.deleteFromCache(10);
lruCache.printCache();
lruCache.deleteFromCache(9);
lruCache.printCache();
}
}