算法之LRU模版1

package com.zhang.reflection.面试.算法模版.LRU;
import java.util.HashMap;
import java.util.Map;

public class LRU {
    class Node<K,V>{
        K key;
        V value;
        Node pre;
        Node next;
        public Node(){
            this.pre=null;
            this.next=null;
        }
        public Node(K key,V value){
            this.key=key;
            this.value=value;
            this.pre=null;
            this.next=null;
        }
    }
    class DoubleLinkedList{
        Node head;
        Node tail;
        public DoubleLinkedList(){
            head=new Node();
            tail=new Node();
            head.next=tail;
            tail.pre=head;
        }
        public void addHead(Node node){
            node.next=head.next;
            node.pre=head;
            head.next.pre=node;
            head.next=node;
        }
        public void removeTail(Node node){
            node.pre.next=node.next;
            node.next.pre=node.pre;
            node.pre=null;
            node.next=null;
        }
        public Node getLast(){
            return tail.pre;
        }
    }
    int cacheSize;
    Map<Integer,Node<Integer,Integer>> map;
    DoubleLinkedList list;
    public LRU(int cacheSize){
        this.cacheSize=cacheSize;
        map=new HashMap<Integer,Node<Integer,Integer>>();
        list=new DoubleLinkedList();
    }
    public int get(int key){
        if(!map.containsKey(key)){
            return -1;
        }
        Node<Integer,Integer> node=map.get(key);
        list.removeTail(node);
        list.addHead(node);
        return node.value;
    }
    public void put(int key,int value){
        if(map.containsKey(key)){
            Node<Integer,Integer> node=map.get(key);
            node.value=value;
            list.removeTail(node);
            list.addHead(node);
        }else{
            if(cacheSize==map.size()){
                Node<Integer,Integer> last = list.getLast();
                map.remove(last.key);
                list.removeTail(last);
            }
            Node<Integer,Integer> node=new Node<>(key,value);
            map.put(key,node);
            list.addHead(node);
        }
    }
    public static void main(String[] args) {
        LRU t=new LRU(3);
        t.put(1,1);
        t.put(2,2);
        t.put(3,3);
        System.out.println(t.map.keySet());
        t.get(1);
        t.put(4,4);
        System.out.println(t.map.keySet());
        t.put(5,5);
        System.out.println(t.map.keySet());
    }
}

全部评论

相关推荐

06-07 00:00
已编辑
腾讯_后端开发
点赞 评论 收藏
分享
05-25 10:45
门头沟学院 Java
Frank_zhan...:没实习一个项目肯定不够,可以再做一个轮子,技术栈再补一个mq,微服务,整体再换个简历模板,暑期尽量再找一个日常实习
无实习如何秋招上岸
点赞 评论 收藏
分享
07-10 11:08
门头沟学院 Java
Sairus:我注册都注册不了提醒我手机号二次啥的,果然对于人才推得就是快,像我投完了就没回音的
投递京东等公司9个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务