import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V> {
public static void main(String[] args) {
// 1 -1 -1 3 4
test1();
System.out.println("-------------------------");
// 1 -1 2
test2();
System.out.println("-------------------------");
// 2 -1
test3();
}
public static void test1() {
LRUCache<Integer, Integer> lruCache = new LRUCache<Integer, Integer>(2, -1);
lruCache.put(1, 1);
lruCache.put(2, 2);
System.out.println(lruCache.get(1));
lruCache.put(3, 3);
System.out.println(lruCache.get(2));
lruCache.put(4, 4);
System.out.println(lruCache.get(1));
System.out.println(lruCache.get(3));
System.out.println(lruCache.get(4));
}
public static void test2() {
LRUCache<Integer, Integer> lruCache = new LRUCache<Integer, Integer>(1, -1);
lruCache.put(2, 1);
System.out.println(lruCache.get(2));
lruCache.put(3, 2);
System.out.println(lruCache.get(2));
System.out.println(lruCache.get(3));
}
public static void test3() {
LRUCache<Integer, Integer> lruCache = new LRUCache<Integer, Integer>(2, -1);
lruCache.put(2, 1);
lruCache.put(2, 2);
System.out.println(lruCache.get(2));
lruCache.put(1, 1);
lruCache.put(4, 1);
System.out.println(lruCache.get(2));
}
public LRUCache(int capacity) {
this(capacity,null);
}
public LRUCache(int capacity, V defaultValue) {
this.capacity = capacity;
this.defaultValue = defaultValue;
head = new Node<>();
tail = new Node<>();
head.next = tail;
tail.prev = head;
}
private Map<K, Node<K, V>> cache = new HashMap<>();
private int capacity;
private int size;
private V defaultValue;
private Node<K, V> head, tail;
public V get(K k) {
Node<K, V> node = cache.get(k);
if (node == null) {
return defaultValue;
} else {
moveToHead(node);
return node.v;
}
}
public void put(K k, V v) {
Node<K, V> node = cache.get(k);
if (node == null) {
node = new Node<>(k, v);
cache.put(k, node);
addToHead(node);
size++;
if (size > capacity) {
removeTail();
size--;
}
} else {
node.v = v;
moveToHead(node);
}
}
private void addToHead(Node node) {
node.prev = head;
node.next = head.next;
head.next.prev = node;
head.next = node;
}
private void removeTail() {
Node<K, V> last = tail.prev;
last.prev.next = last.next;
last.next.prev = last.prev;
cache.remove(last.k);
}
private void moveToHead(Node<K, V> node) {
Node<K, V> first = head.next;
if (first == node) {
return;
}
Node prev = node.prev;
Node next = node.next;
if (prev != null) {
prev.next = next;
}
if (next != null) {
next.prev = prev;
}
node.prev = first.prev;
node.next = first;
first.prev = node;
head.next = node;
}
private class Node<K, V> {
K k;
V v;
Node<K, V> prev;
Node<K, V> next;
public Node() {
}
public Node(K k, V v) {
this.k = k;
this.v = v;
}
public Node(K k, V v, Node<K, V> prev, Node<K, V> next) {
this.k = k;
this.v = v;
this.prev = prev;
this.next = next;
}
}
}
LRUCache:双向链表+Map
猜你喜欢
转载自blog.csdn.net/qq_30038111/article/details/115497556
今日推荐
周排行