实现LRU

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

public static class Node<V>{
		public V value;
		public Node<V> last;
		public Node<V> next;
		
		public Node(V value) {
			this.value=value;
		}
	}
	
	public static class NodeDoubleLinkedList<V>{
		//自制一个双向链表
		private Node<V>head;
		private Node<V>tail;
		
		public NodeDoubleLinkedList() {
			this.head=null;
			this.tail=null;
		}
	public void addNode(Node<V>newNode) {
		if (newNode==null) {
			//传进来的是个空值,不管
			return;
		}
		if(this.head==null) {
			//原来链表为空
			this.head=newNode;
			this.tail=newNode;
		}else {
			this.tail.next=newNode;
			newNode.last=this.tail;
			this.tail=newNode;
		}
	}
	public void moveNodeToTail(Node<V>node) {
		if(this.tail==node) {
			//待移动的节点在末尾
			return;
		}
		if(this.head==node) {
			//待移动的节点是头节点
			this.head=node.next;
			this.head.last=null;
		}else {
			node.last.next=node.next;
			node.next.last=node.last;
		}
		node.last=this.tail;
		node.next=null;
		this.tail.next=node;
		this.tail=node;
	}
	
	public Node<V>removeHead(){
		if(this.head==null) {
			return null;
		}
		Node<V>res=this.head;
		if(this.head==this.tail) {
			//只有一个节点
			this.head=null;
			this.tail=null;
		}else {
			this.head=res.next;
			res.next=null;
			this.head.last=null;
		}
		return res;
	}
}
	
	public static class MyCache<K,V>{
		private HashMap<K,Node<V>>keyNodeMap;
		private HashMap<Node<V>,K>NodeKeyMap;
		private NodeDoubleLinkedList<V>nodeList;
		private int capacity;
		
		public MyCache(int capacity) {
			if(capacity<1) {
				throw new RuntimeException("should be more than 0.");
			}
			//初始化
			this.keyNodeMap=new HashMap<K,Node<V>>();
			this.NodeKeyMap=new HashMap<Node<V>,K>();
			this.nodeList=new NodeDoubleLinkedList<V>();
			this.capacity=capacity;
		}
		
		//对某个key值所对应的节点查询,移动节点
		public V get(K key) {
			if(this.keyNodeMap.containsKey(key)) {
				//如果包含key
				Node<V>res=this.keyNodeMap.get(key);
				//将节点移动到末尾
				this.nodeList.moveNodeToTail(res);
				//返回要查询的值
				return res.value;
			}
			//如果双向列表中无此节点,返回空
			return null;
		}
		//设置节点的值,只要修改,移动节点
		public void set(K key,V value) {
			if(this.keyNodeMap.containsKey(key)) {
				Node<V>node=this.keyNodeMap.get(key);
				node.value=value;
				this.nodeList.moveNodeToTail(node);
			}else {
				Node<V>newNode=new Node<V>(value);
				this.keyNodeMap.put(key, newNode);
				this.nodeList.addNode(newNode);
				if(this.keyNodeMap.size()==this.capacity+1) {
					this.removeMostUnsedCache();
				}
			}
		}
		
		//当内存不够时,移除最不经常使用的节点
		private void removeMostUnsedCache() {
			Node<V>removeNode=this.nodeList.removeHead();
			K removeKey=this.NodeKeyMap.get(removeNode);
			this.keyNodeMap.remove(removeKey);
		}
		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值