public class LRUCache {
class DoubleLinkedList {
int key;
int val;
DoubleLinkedList prev;
DoubleLinkedList next;
public DoubleLinkedList(){}
public DoubleLinkedList(int key, int val) {
this.key = key;
this.val = val;
}
}
// parameters
private HashMap<Integer, DoubleLinkedList> cache;
private int count, capacity;
private DoubleLinkedList head, tail;
// constructor
public LRUCache(int capacity) {
this.cache = new HashMap<Integer, DoubleLinkedList>();
this.count = 0;
this.capacity = capacity;
head = new DoubleLinkedList();
head.prev = null;
tail = new DoubleLinkedList();
tail.next = null;
head.next = tail;
tail.prev = head;
}
public void addNodeFirst(DoubleLinkedList node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
public void removeNode(DoubleLinkedList node) {
DoubleLinkedList pre = node.prev;
DoubleLinkedList post = node.next;
pre.next = post;
post.prev = pre;
}
public void moveToHead(DoubleLinkedList node) {
removeNode(node);
addNodeFirst(node);
}
public DoubleLinkedList popTail() {
DoubleLinkedList pre = tail.prev;
removeNode(pre);
return pre;
}
public int get(int key) {
DoubleLinkedList node = cache.get(key);
if (node == null) {
return -1;
}
moveToHead(node);
return node.val;
}
public void set(int key, int value) {
DoubleLinkedList node = cache.get(key);
if (node == null) {
DoubleLinkedList newNode = new DoubleLinkedList(key, value);
cache.put(key, newNode);
addNodeFirst(newNode);
count++;
if (count > capacity) {
DoubleLinkedList tail = popTail();
cache.remove(tail.key);
count--;
}
} else {
node.val = value;
moveToHead(node);
}
}
}
public class LRUCache {
private Map<Integer, Integer> cache;
private int capacity;
public LRUCache(int capacity) {
this.cache = new LinkedHashMap<Integer, Integer>();
this.capacity = capacity;
}
public int get(int key) {
Integer val = cache.get(key);
if (val == null) {
return -1;
}
cache.remove(key);
cache.put(key, val);
return val;
}
public void set(int key, int value) {
cache.remove(key);
cache.put(key, value);
if (cache.size() > capacity) {
cache.remove(cache.keySet().iterator().next());
}
}
}