LRU

Java实现最近最少使用


package com.leetcode.design;

import java.util.Hashtable;

public class LRU {
private Hashtable<Integer,DLinkedNode> cache = new Hashtable<Integer,DLinkedNode>();
private int count;
private int capacity;
private DLinkedNode head,tail;

public LRU(int capacity){
this.capacity = capacity;
this.count = 0;
head = new DLinkedNode();
head.pre = null;
tail = new DLinkedNode();
tail.post = null;

head.post = tail;
tail.pre = head;
}

public int get(int key){
DLinkedNode node = cache.get(key);
if(node == null){
return -1;
}
this.removeToHead(node);
return node.value;
}

public void set(int key,int value){
DLinkedNode node = cache.get(key);
if(node == null){
DLinkedNode newNode = new DLinkedNode();
newNode.key = key;
newNode.value = value;
this.cache.put(key,newNode);
this.addNode(newNode);
++count;
if(count>capacity){
DLinkedNode tail = this.popTail();
this.cache.remove(tail.key);
--count;
}
}else{
node.value = value;
this.removeToHead(node);
}
}

private DLinkedNode popTail() {
DLinkedNode res = tail.pre;
this.removeNode(res);
return res;
}

private void removeToHead(DLinkedNode node) {
this.removeNode(node);
this.addNode(node);
}

private void removeNode(DLinkedNode node) {
DLinkedNode pre = node.pre;
DLinkedNode post = node.post;
pre.post = post;
post.pre = pre;
}

private void addNode(DLinkedNode node) {
node.pre = head;
node.post = head.post;

head.post.pre = node;
head.post = node;
}

}

创建一个hashtable的缓存,并在构造函数中初始化头节点、尾节点和最大容量,每获取一次存在的节点,均将该节点移动到头部,每加入一个节点,首先判断是否存在该节点,若存在则put替换旧的节点,计数加一,并将其移动到头部,然后判断是否超过最大容量,若超过则移除尾部节点,计数减一

原文地址:https://www.cnblogs.com/kangaroohu/p/9605764.html