1. LRU 缓存
2. 代码实现
class LRUCache {
int capacity;
HashMap<Integer,Node> table;
LinkedList<Integer> queue;
Node head,tail;
int size=0;
public LRUCache(int capacity) {
this.capacity=capacity;
this.table=new HashMap<>();
this.queue=new LinkedList<>();
this.head=new Node();
this.tail=new Node();
this.head.next=this.tail;
this.tail.pre=this.head;
}
public int get(int key) {
if(!table.containsKey(key)){
return -1;
}
Node node=table.get(key);
int val=node.val;
removeNode(node);
addToTail(node);
return val;
}
public void removeNode(Node node){
size--;
Node left=node.pre,right=node.next;
left.next=right;
right.pre=left;
}
public void addToTail(Node node){
size++;
Node last=tail.pre;
last.next=node;
node.pre=last;
node.next=tail;
tail.pre=node;
}
public void put(int key, int value) {
if(get(key)!=-1){
table.get(key).val=value;
return;
}
Node node=new Node(key,value);
table.put(key,node);
if(size==capacity){
int k=head.next.key;
removeNode(head.next);
table.remove(k);
}
addToTail(node);
}
void printList(Node node){
Node temp=head.next;
while(temp!=tail){
System.out.print(temp.val+" ");
temp=temp.next;
}
System.out.println();
}
class Node{
int key;
int val;
Node pre;
Node next;
public Node(){
}
public Node(int key,int val){
this.key=key;
this.val=val;
}
}
}