import lombok.Data;
import java.util.HashMap;
import java.util.Map;
public class LRUCache {
Node head, tail;
Map<Integer, Node> map;
int capacity;
@Data
class Node {
Node prev, next;
int key, val;
Node(int key, int val) {
this.key = key;
this.val = val;
}
public String toString() {
int key1 = -1;
if (prev != null) {
key1 = prev.key;
}
int key2 = -1;
if (next != null) {
key2 = next.key;
}
return key1 + "<--key(" + key + ")-->" + key2;
}
}
public static void main(String[] args) {
LRUCache lruCache = new LRUCache(3);
for (int i = 0; i < 10; i++) {
lruCache.put(i, i);
}
System.out.println("get8>>>>>");
System.out.println(lruCache.get(8));
System.out.println("get7>>>>>");
System.out.println(lruCache.get(7));
System.out.println("get8>>>>>");
System.out.println(lruCache.get(8));
System.out.println("get9>>>>>");
System.out.println(lruCache.get(9));
}
public LRUCache(int capacity) {
map = new HashMap<Integer, Node>(capacity);
this.capacity = capacity;
}
public int get(int key) {
Node item = map.get(key);
if (item != null) {
resetHead(item);
return item.val;
}
return -1;
}
private void resetHead(Node item) {
if (item.next == null) {
item.prev.next = null;
tail = item.prev;
} else {
item.prev.next = item.next;
item.next.prev = item.prev;
}
System.out.println("-----移动节点----");
for (Node x = head; x != null; x = x.next) {
System.out.println(x.toString());
}
addToHead(item);
}
public void put(int key, int value) {
Node item = new Node(key, value);
map.put(key, item);
addToHead(item);
trim();
}
private void trim() {
if (map.size() > capacity) {
Node tailNode = removeTail();
map.remove(tailNode.key);
}
}
private Node removeTail() {
Node tailNode = tail;
if (tail == null) {
System.out.println("队列为空");
return null;
}
tail.prev.next = null;
tail = tail.prev;
System.out.println("-----删除节点");
for (Node x = head; x != null; x = x.next) {
System.out.println(x);
}
return tailNode;
}
private void addToHead(Node item) {
if (item == null || item.equals(head)) {
return;
}
Node f = head;
item.prev = null;
head = item;
if (f != null) {
item.next = f;
f.prev = item;
} else {
tail = item;
}
System.out.println("添加节点----");
for (Node x = head; x != null; x = x.next) {
System.out.println(x.toString());
}
}
}