LRU算法java版

基于双向链表+hash表

节点对象

public class Node<K,V> {
    public K key;
    public V value;
    public Node<K,V> prev;
    public Node<K,V> next;

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

    public Node() {
    }


}
public class LruCache<V> {

    /**
    容量
     */
    private int capacity=1024;
    /**
     * Node记录表
     */
    private Map<String,Node<String,V>> table=new ConcurrentHashMap<>();
    /**
     * 双向链表头部
     */
    private Node<String,V> head;
    /**
     * 双向链表尾部
     */
    private Node<String,V> tail;


    public LruCache(int capacity) {
        this();
        this.capacity = capacity;
    }

    public LruCache() {
        head=new Node<>();
        tail=new Node<>();
        head.next=tail;
        head.prev=null;
        tail.prev=head;
        tail.next=null;
    }

    public V get(String key){
        Node<String, V> node = table.get(key);
        if(node==null){
            return null;
        }
        node.prev.next=node.next;
        node.next.prev=node.prev;
        //移动节点列表到表头
        node.next=head.next;
        head.next.prev=node;
        node.prev=head;
        head.next=node;
        return node.value;
    }

    public void put(String key,V value){
        Node<String, V> node = table.get(key);
        if(node==null){
            if(table.size()==capacity){
                table.remove(tail.prev.key);
                tail.prev.prev.next=tail;
                tail.prev=tail.prev.prev;
            }
            node=new Node<>();
            node.key=key;
            node.value=value;
            table.put(key,node);
        }else{
            node.value=value;
            table.put(key,node);
        }
        //移动节点列表到表头
        node.next=head.next;
        head.next.prev=node;
        node.prev=head;
        head.next=node;
    }


}

测试

LruCache<Node> cache = new LruCache<>(4);
        Node<String, Integer> node1 = new Node<>("key1", 1);
        Node<String, Integer> node2 = new Node<>("key2", 2);
        Node<String, Integer> node3 = new Node<>("key3", 3);
        Node<String, Integer> node4 = new Node<>("key4", 4);
        Node<String, Integer> node5 = new Node<>("key5", 5);
        cache.put("key1", node1);
        cache.put("key2", node2);
        cache.put("key3", node3);
        cache.put("key4", node4);
        cache.get("key2");
        cache.put("key5", node5);
        cache.get("key2");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值