class LNode {
String key;
Object data;
public LNode(String key, Object data) {
this.data = data;
this.key = key;
}
}
class LRU {
final int max;
int count;
LinkedList<LNode> list = new LinkedList<LNode>();
Map<String, LNode> map = new HashMap<String, LNode>();
public LRU(int max) {
this.max = max;
this.count = 0;
}
public void insert(String key, LNode node) {
LNode value = map.get(key);
if(value != null) {
list.remove(value);
list.addLast(node);
map.put(key, node);
} else {
if(count < max) {
map.put(key, node);
list.addLast(node);
count++;
}else{
LNode reNode = list.removeFirst();
list.addLast(node);
map.remove(reNode.key);
map.put(key, node);
}
}
}
public void remove(String key) {
if(count > 0 && map.containsKey(key)){
LNode node = map.get(key);
if(node != null){
list.remove(node);
map.remove(key);
count--;
}
}
}
public void print(){
for(Map.Entry<String, LNode> entry : map.entrySet()){
System.out.println("[" + entry.getKey() + " , " + entry.getValue().data + "]");
}
Aron.line();
for(LNode node : list){
System.out.println("["+ node.data + "]");
}
}
}