Leetcode_146_LRU缓存_数据结构

class Node {
    Node pre, next;
    int key, value;

    public Node() {
    }

    public Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

class LRUCache {
    Node head, tail;
    Map<Integer, Node> map;
    int capacity;
    int size;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.size = 0;
        map = new HashMap<>();
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
    }

    public int get(int key) {
        Node node = map.get(key);
        if(node != null) {
            removeNode(node);
            addNodeToHead(node);
            return node.value;
        }
        return -1;
    }

    public void put(int key, int value) {
        Node node = map.get(key);
        if(node != null) {
            removeNode(node);
            node.value = value;
            addNodeToHead(node);
        } else {
            node = new Node(key, value);
            addNodeToHead(node);
            if(size == capacity) {
                map.remove(removeTail().key);
            } else {
                size ++;
            }
        }
        // capacity若为0的话,需要判断size
        map.put(key, node);
    }

    void removeNode(Node node) {   
        node.pre.next = node.next;
        node.next.pre = node.pre;
        node.next = null;
        node.pre = null;
    }

    void addNodeToHead(Node node) {
        node.next = head.next;
        node.pre = head;
        head.next = node;
        node.next.pre = node;
    }

    Node removeTail() {
        Node temp = tail.pre;
        temp.pre.next = tail;
        tail.pre = temp.pre;
        temp.next = null;
        temp.pre = null;
        return temp;
    }
}

你可能感兴趣的:(daily_algorithm,数据结构,leetcode,算法,职场和发展)