缓存过期清除策略之LRU算法

class LRUCache{
    Node head;
    Node end;
    int limit;
    HashMap map = new HashMap<>();
    public LRUCache(int limit) {
        this.limit = limit;
    }
    
    public String get(String key) {
        Node node = map.get(key);
        if (node == null) return null;
        refresh(node);
        return node.val;
    }
    
    public void put(String key, String val) {
        Node node = map.get(key);
        if (node == null) {
            if (map.size() >= limit) {
                String oldkey = removeNode(head);
                map.remove(oldkey);
            }
            Node tmp = new Node(key, val);
            map.put(key, tmp);
            appendNode(node);
        }else {
            node.val = val;
            refresh(node);
        }
    }
    public void refresh(Node node) {
        if (end == node) {
            return;
        }
        removeNode(node);
        appendNode(node);
    }
    public String removeNode(Node node) {
        if (end == node) {
            end = end.pre;
        }else if (head == node) {
            head = head.next;
        }else {
            node.pre.next = node.next;
            node.next.pre = node.pre;
        }
        return node.key;
    }
    public void appendNode(Node node) {
        if (end != null) {
            end.next = node;
            node.pre = end;
            node.next = null;
        }
        end = node;
        if (head == null) {
            head = node;
        }
    }
    
}

class Node{
    String key;
    String val;
    Node pre;
    Node next;
    public Node(String key, String val) {
        this.key = key;
        this.val = val;
    }
}

 

你可能感兴趣的:(算法,面试)