package com.example.suanfa;
import java.util.HashMap;
import java.util.Map;
public class LRUCache<K, V> {
int capacity;
class Node {
private Node pre;
private Node next;
private K key;
private V val;
public Node(K key, V val) {
this.key = key;
this.val = val;
}
public Node() {
}
}
private Node head;
private Node tail;
Map<K, Node> map;
LRUCache(int capacity) {
this.capacity = capacity;
this.map = new HashMap<>();
this.head = new Node(null, null);
this.tail = new Node(null, null);
tail.pre = head;
head.next = tail;
}
public V get(K key) {
Node node = map.get(key);
if (node == null) {
//为空则添加,相当于从数据库中查询数据,然后塞进cache中
return put(key, (V) key);
}
//不为空,将该节点调至队头
unlinkNode(node);
addFirst(node);
return node.val;
}
public V put(K key, V val) {
Node node = new Node(key, val);
addFirst(node);
map.put(key, node);
if (map.size() > capacity) {
//需要删除队尾的节点
Node delNode = removeLast();
map.remove(delNode.key);
}
return node.val;
}
private void unlinkNode(Node node) {
node.pre.next = node.next;
node.next.pre = node.pre;
node.pre = null;
node.next = null;
}
private void addFirst(Node node) {
Node next = head.next;
node.next = next;
next.pre = node;
head.next = node;
node.pre = head;
}
private Node removeLast() {
Node node = tail.pre;
tail.pre = node.pre;
node.pre.next = tail;
node.pre = null;
node.next = null;
return node;
}
public int getCapacity() {
return map.size();
}
public int getMaxCapacity() {
return capacity;
}
public void traverseCacheBuffer() {
Node p = head;
while (p != null) {
if (p.val != null) {
if (p.next != tail) {
System.out.print(p.val + "-->");
} else {
System.out.print(p.val);
}
}
p=p.next;
}
System.out.println();
}
public static void main(String[] args) {
LRUCache<Integer, Integer> cache = new LRUCache<>(5);
int array[] = {1, 2, 1, 3, 5, 6, 8, 9, 6, 1, 3, 4};
for (int i = 0; i < array.length; i++) {
System.out.println("val is:" + cache.get(array[i]) + "----------map size is:" + cache.getCapacity());
}
cache.traverseCacheBuffer();
}
}