java
复制代码
public class LRUCache {
class Node{
int key;
int value;
Node prev;
Node next;
public Node(int key, int value) {
this.key = key;
this.value = value;
this.prev = null;
this.next = null;
}
}
int capacity;//容量,最大可以存储多少个节点
int currSize;//当前存储的节点数
Node head, tail;//头节点,尾节点
Map<Integer, Node> map = new HashMap<>();//key-value
public LRUCache(int capacity) {
this.capacity = capacity;
}
public int get(int key) {
if(map.containsKey(key)){
Node node = map.get(key);
removeNode(node);
return node.value;
}
return -1;
}
public void put(int key, int value) {
if(map.containsKey(key)){
Node node = map.get(key);
node.value = value;
removeNode(node);
} else {
if(currSize == capacity){
map.remove(head.key);
removeNode(head);
/*if(capacity == 1) {//当前只有一个节点
head.key = key;
head.value = value;
} else {//当前节点不是尾节点,则他会被放到尾节点
tail.key = key;
tail.value = value;
}*/
tail.key = key;
tail.value = value;
map.put(key, tail);
} else if(currSize < capacity){
Node node = new Node(key, value);
map.put(key, node);
if(currSize == 0) {//当前没有节点
head = node;
tail = node;
} else {
tail.next = node;
node.prev = tail;
tail = node;
}
currSize++;
}
}
}
//将节点node移动到链表尾
public void removeNode(Node node){
if(node.next == null) return;
if(node.prev == null) {//当前节点是头节点
head = node.next;
node.next.prev = null;
node.next = null;
tail.next = node;
node.prev = tail;
tail = node;
} else {//当前节点不是头节点和尾节点
node.prev.next = node.next;
node.next.prev = node.prev;
node.next = null;
node.prev = tail;
tail.next = node;
tail = node;
}
}
public static void main(String[] args) {
String[] str = {"LRUCache","put","get","put","get","get"};
int[][] arr = {{1},{2,1},{2},{3,2},{2},{3}};
LRUCache lruCache = null;
List<Integer> list = new ArrayList<>();
for(int i = 0; i < str.length; i++) {
if(str[i].equals("LRUCache")) {
lruCache = new LRUCache(arr[i][0]);
}
if(str[i].equals("put")) {
lruCache.put(arr[i][0], arr[i][1]);
}
if(str[i].equals("get")) {
list.add(lruCache.get(arr[i][0]));
continue;
}
list.add(null);
}
System.out.println(list);
}
}