class LRUCache {
//自建一个类
class DNode{
int k;
int v;
DNode pre;
DNode next;
public DNode(){};
public DNode(int kk,int vv){k = kk;v = vv;};
}
//自己的属性
private int size;
private int capacity;
private DNode head,tail;
private HashMap<Integer,DNode> map = new HashMap<>();
public LRUCache(int capacity) {
this.size = 0;
this.capacity = capacity;
head = new DNode();
tail = new DNode();
head.next = tail;
tail.pre = head;
}
public int get(int key) {
DNode c = map.get(key);
if(c == null) return -1;
// 把原来的删除
c.pre.next = c.next;
c.next.pre = c.pre;
// 重新插入 和head产生关联
DNode og = head.next ;
head.next = c;
c.pre = head ;
c.next = og;
og.pre = c;
return c.v;
}
public void put(int key, int value) {
//分两种情况 有或者没有
DNode c = map.get(key);
if(c == null){
//新建 插到头节点去
DNode newnode = new DNode(key,value);
map.put(key,newnode);
size++;
DNode og = head.next ;
head.next = newnode;
newnode.pre = head ;
newnode.next = og;
og.pre = newnode;
if(size > capacity){
//删除尾节点
DNode bye = tail.pre;
bye.pre.next = bye.next;
bye.next.pre = bye.pre;
//从map移除
map.remove(bye.k);
//size--
size--;
}
}else{
c.v = value;
//还是要remove啊 好累我草
c.next.pre = c.pre;
c.pre.next = c.next;
// 重新插入 和head产生关联
DNode og = head.next ;
head.next = c;
c.pre = head ;
c.next = og;
og.pre = c;
}
}
}