java实现LRU

import org.apache.bcel.generic.LREM;

import java.util.HashMap;
import java.util.Map;

/**
 * @author yuchen
 * @version 1.0
 * @date 2020-05-11 17:18
 */
public class LruCache {

    class Node{
        int key;
        int val;
        Node prev;
        Node next;
    }

    private int capacity;

    private Node first;

    private Node last;

    private Map map;

    public LruCache(int capacity){
        this.capacity = capacity;
        map = new HashMap<>(capacity);
    }

    public int get(int key){

        Node node = map.get(key);

        if(node==null){
            return -1;
        }

        moveToHead(node);

        return node.val;

    }

    public void moveToHead(Node node){

        if(node == first){//头节点
            return;
        }else if(node == last){//尾节点 直接移除即可
            last.prev.next = null;
            last = last.prev;
        }else {
            //中间节点
            Node preNode = node.prev;
            Node lastNode = node.next;

            preNode.next = lastNode;
            lastNode.prev = preNode;

            node.next = first;
            first.prev = node;

            first = node;
        }

    }

    public void put(int key,int value){

        Node node = map.get(key);

        if(node == null){

            node = new Node();
            node.key = key;
            node.val = value;

            if(map.size() == capacity){
                removeLastNode();
            }

            addToHead(node);
            map.put(key,node);
        }
    }

    public void removeLastNode(){

        map.remove(last.key);
        Node preNode = last.prev;
        if(preNode!=null){
            preNode.next = null;
            last = preNode;
        }
    }


    public void addToHead(Node node){
        if(map.isEmpty()){
            first = node;
            last = node;
        }else{
            node.next = first;
            first.prev = node;
            first = node;
        }
    }

    @Override
    public String toString(){
        return map.keySet().toString();
    }

    public static void main(String[] args) {
        LruCache lruCache = new LruCache(5);
        lruCache.put(1,1);
        lruCache.put(2,2);
        lruCache.put(3,3);
        lruCache.put(4,4);
        lruCache.put(5,5);

//        for(int key : lruCache.map.keySet()){
//            System.out.println(key);
//        }

        lruCache.get(5);
        System.out.println("=====");

        for(int key : lruCache.map.keySet()){
            System.out.println(key);
        }
    }

}

 

你可能感兴趣的:(简单小算法)