LRU Cache

来源:互联网 发布:蜀山缥缈录捏脸数据 编辑:程序博客网 时间:2024/06/07 06:11

定义的Node中的key是有用的:用于从map中删掉the least used Node。

public class LRUCache {    private class Node{        Node prev;        Node next;        int value;        int key;        public Node(int key, int value) {            this.key = key;            this.value = value;            this.prev = null;            this.next = null;        }    }    private int capacity;    private HashMap<Integer, Node> map = new HashMap<Integer, Node>();    private Node head = new Node(-1, -1);    private Node tail = new Node(-1, -1);        public LRUCache(int capacity) {        this.capacity = capacity;        tail.prev = head;        head.next = tail;        head.prev = tail;        tail.next = head;    }    public int get(int key) {        if (!map.containsKey(key)) {            return -1;        }        Node node = map.get(key);        node.prev.next = node.next;        node.next.prev = node.prev;        moveToTail(node);        return node.value;    }    public void set(int key, int value) {        if (get(key) != -1) {            map.get(key).value = value;            return;        }                if (capacity == map.size()) {            Node removedNode = head.next;            map.remove(removedNode.key);            head.next = removedNode.next;            removedNode.next.prev = head;        }        Node node = new Node(key, value);        moveToTail(node);        map.put(key, node);    }        private void moveToTail(Node node) {        node.next = tail;        node.prev = tail.prev;        tail.prev.next = node;        tail.prev = node;    }}


0 0
原创粉丝点击