栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LRU(Java实现)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LRU(Java实现)

public class LRU {
    final static int MAXSIZE = 5;
    public static void main(String[] args) {
        // 用来存储缓存
        HashMap cache = new HashMap<>();
        Node head = new Node<>(0,"0");
        myPut(cache,new Node(1,"a") , head);
        myPut(cache,new Node(2,"b"), head);
        myPut(cache,new Node(3,"c"), head);
        myPut(cache,new Node(4,"d"), head);
        myPut(cache,new Node(5,"e"), head);
        myPut(cache,new Node(6,"f"), head);
        myPut(cache,new Node(7,"g"), head);
        System.out.println(myGet(cache, head, 4));


    }


    public static void myPut(Map cache , Node node , Node head){
        Node p = head;
        // 先把node添加到队头
        node.next = p.next;
        p.next = node;
        // 缓存数量达到上限
        if (cache.size() >= MAXSIZE){
            // 遍历到队尾删除最后一个元素
            for (int i = 0 ; i < MAXSIZE ; i++){
                p = p.next;
            }
            // 删除缓存中的元素
            cache.remove(node.key);
            p.next = null;
        }
        // node添加到缓存中
        cache.put(node.key,node.value);
        Node temp = head.next;
        while (temp != null){
            System.out.print(temp.value+"->");
            temp = temp.next;
        }
        System.out.println();
    }

    public static String myGet(Map cache , Node head , Integer key){
        Node p = head;
        String res = null;
        // key存在
        if (cache.containsKey(key)){
            // 获取value
            res = cache.get(key);
            // 找到p
            while (p.next.key != key){
                p = p.next;
            }
            // 被获取的元素放入队头
            Node temp = p.next;
            p.next = temp.next;
            temp.next = head.next;
            head.next = temp;
        }
        Node temp = head.next;
        while (temp != null){
            System.out.print(temp.value+"->");
            temp = temp.next;
        }
        System.out.println();
        return res;
    }
}


class Node{

    K key;
    V value;
    Node next;

    public Node(K key, V value) {
        this.key = key;
        this.value = value;
        this.next = null;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/458912.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号