package lru;
import java.util.HashMap;
public class LRUCache {
class Node {
int key;
String value;
Node pre;
Node post;
}
private int count;
private int capacity;
private HashMap<Integer, Node> cache = new HashMap<>();
private Node head;
private Node tail;
public LRUCache(int capacity) {
this.count = 0;
this.capacity = capacity;
head = new Node();
tail = new Node();
head.pre = null;
head.post = tail;
tail.pre = head;
tail.post = null;
}
public String get(int key) {
Node node = cache.get(key);
if (node == null) {
return "-1";
}
delete(node);
addHead(node);
return node.value;
}
public void put(int key, String value) {
Node node = cache.get(key);
if (node != null) {
node.value = value;
delete(node);
addHead(node);
return;
}
node = new Node();
node.key = key;
node.value = value;
cache.put(key, node);
addHead(node);
count++;
if (count > capacity) {
removeTail();
}
}
public void delete(Node node) {
node.pre.post = node.post;
node.post.pre = node.pre;
}
public void addHead(Node node) {
node.pre = head;
node.post = head.post;
head.post.pre = node;
head.post = node;
}
public void removeTail() {
Node node = tail.pre;
tail.pre = node.pre;
node.pre.post = tail;
cache.remove(node.key);
count--;
}
}
LRU代码实现
最新推荐文章于 2024-04-11 10:38:53 发布