LRUCache Java实现

 

LFUCache Java实现

 

实现1:

import java.util.LinkedHashMap;
import java.util.HashMap;
import java.lang.IllegalArgumentException;
import java.util.Map;

public class LRUCache extends LinkedHashMap{
	
	private int size;
	
	public LRUCache(int size){
		if(size <= 0){
			throw new IllegalArguementException("invalid size");
		}
		
		super(size);
		this.size = size;
	}

	@Override
	public boolean removeEldestEntry(Map.Entry entry){
		return this.size() > size;
	}
}

 

实现2:

import java.util.HashMap;

public class LRUCache{

	private HashMap> cache;
	private Node head;
	private Node tail;
	private int size;

	private LRUCache(int size){
		if(size <= 0){
			throw new IllegalArgumentException("invalid size");
		}

		cache = new HashMap(size);
		this.size = size;
	}

	public void put(K key, V value){
		if(cache.containsKey(key)){
			removeNode(cache.get(key));
		}else if(cache.size() == size){
			cache.remove(head.getKey());
			removeNode(head);
		}

		Node node = new Node(key, value);
		cache.put(key, node);
		addNode(node);
	}

	public V get(K key){
		if(!cache.containsKey(key)){
			return null;
		}

		Node node = cache.get(key);
		removeNode(node);
		addNode(node);
		return node.getValue();
	}

	private void removeNode(Node node){
		Node pre = node.getPre();
		Node next = node.getNext();

		if(node != head && node != tail){
			pre.next = next;
			node.pre = pre;
		}else {
			if (node == this.head) {
				this.head = next;
				if (null != next) {
					next.pre = null;
				}
			}
			if (node == this.tail) {
				this.tail = pre;
				if (null != pre) {
					pre.next = null;
				}
			}
		}
	}

	private void addNode(Node node){
		if(null == head && null == tail){
			head = node;
			tail = node;
			return;
		}

		this.tail.next = node;
		node.pre = this.tail;
		this.tail = node;
	}

	public static class Node{
		private K key;
		private V value;
		private Node pre;
		private Node next;

		public Node(K key, V value){
			this.key = key;
			this.value = value;
		}

		public Node(K key, V value, Node pre, Node next){
			this.key = key;
			this.value = value;
			this.pre = pre;
			this.next = next;
		}

		public K getKey(){
			return this.key;
		}

		public V getValue(){
			return this.value;
		}

		public Node getPre(){
			return this.pre;
		}

		public Node getNext(){
			return this.next;
		}
	}
}

 

你可能感兴趣的:(算法题)