public class LRUCache {
private Map<Integer, DoubleLinkedListNode> map = new HashMap<Integer, DoubleLinkedListNode>();
private DoubleLinkedListNode head;
private DoubleLinkedListNode tail;
private int len;
private int capacity;
public LRUCache(int capacity) {
this.capacity = capacity;
len=0;
}
public int get(int key) {
if (map.containsKey(key)) {
DoubleLinkedListNode latest = map.get(key);
removeNode(latest);
setHead(latest);
return latest.val;
} else {
return -1;
}
}
public void removeNode(DoubleLinkedListNode node) {
DoubleLinkedListNode curr = node;
DoubleLinkedListNode before = node.prev;
DoubleLinkedListNode after = node.next;
if (before != null) {
before.next = after;
} else {
head = after;
}
if (after != null) {
after.prev = before;
} else {
tail = before;
}
}
public void setHead(DoubleLinkedListNode node) {
node.next = head;
node.prev = null;
if (head != null) {
head.prev = node;
}
head = node;
if (tail==null) {
tail = node;
}
}
public void set(int key, int value) {
if (map.containsKey(key)) {
DoubleLinkedListNode oldNode = map.get(key);
oldNode.val = value;
removeNode(oldNode);
setHead(oldNode);
} else {
DoubleLinkedListNode newNode = new DoubleLinkedListNode(key, value);
if (len < capacity) {
setHead(newNode);
map.put(key, newNode);
len++;
} else {
map.remove(tail.key);
tail = tail.prev;
if (tail!=null) {
tail.next = null;
}
setHead(newNode);
map.put(key, newNode);
}
}
}
}
class DoubleLinkedListNode {
public int val;
public int key;
public DoubleLinkedListNode prev;
public DoubleLinkedListNode next;
public DoubleLinkedListNode(int key, int val) {
this.val = val;
this.key = key;
}
}
No comments:
Post a Comment