新建一个带有头尾节点的链表,链表存放KV对,用HashMap存储Key到链表节点的映射。插入时,若已经存在,则先将其删除,之后将其插入链表头部,若插入之后缓存中节点数大于缓存容量,则将链表尾部节点删除;查找时,将其放到链表头部,表示该节点最近被访问过
private int capacity = 0;
private Map<Integer, Node> map = new HashMap<Integer, Node>();
private class Node {
public Node pre, next;
public int key, val;
}
private Node head = new Node();
private Node tail = new Node();
public LRUCache(int capacity) {
this.capacity = capacity;
head.next = tail;
tail.pre = head;
}
public void removeNode(Node node) {
Node pre = node.pre;
Node next = node.next;
pre.next = next;
next.pre = pre;
node = null;
}
public int get(int key) {
if (map.containsKey(key)) {
Node t = map.get(key);
removeNode(map.get(key));
t.next = head.next;
head.next.pre = t;
t.pre = head;
head.next = t;
return t.val;
}
else
return -1;
}
public void put(int key, int value) {
if (map.containsKey(key)) {
removeNode(map.get(key));
}
Node t = new Node();
t.key = key;
t.val = value;
t.next = head.next;
head.next.pre = t;
t.pre = head;
head.next = t;
map.put(key, t);
if (map.size() > this.capacity) {
Node pre = tail.pre;
map.remove(pre.key);
tail.pre = pre.pre;
removeNode(pre);
}
return;
}