WHCSRL 技术网

利用双向链表实现LRU算法(leetcode146)

class LRUCache {

    private int capacity;
    private Map<Integer, Node> cache;
    private Node head;
    private Node tail;

    public LRUCache(int capacity) {
        this.capacity = capacity;
        this.cache = new HashMap<>();
    }

    public int get(int key) {
        Node res = cache.get(key);
        if (res == null) {
            return -1;
        }
        put(key, res.val);
        return res.val;
    }

    public void put(int key, int value) {
        Node newNode = new Node(key, value);
        if (cache.containsKey(key)) {
            removeNode(cache.get(key));
            addHead(newNode);
            cache.put(key, newNode);
        } else {
            if (cache.size() == capacity) {
                Node x = removeTail();
                cache.remove(x.key);
                addHead(newNode);
                cache.put(key, newNode);
            } else {
                addHead(newNode);
                cache.put(key, newNode);
            }
        }
    }

    public Node removeTail() {
        Node temp = tail;
        Node pre = tail.pre;
        if (pre == null) {
            //0号节点
            head = null;
            tail = head;
            return temp;
        }
        pre.next = null;
        tail = pre;
        return temp;
    }

    public void addHead(Node x) {
        if (head == null) {
            head = x;
            tail = head;
            return;
        }
        x.next = head;
        head.pre = x;
        head = x;
    }

    public void removeNode(Node x) {
        Node pre = x.pre;
        Node next = x.next;
        if (pre == null) {
            if (next == null) {
                head = null;
                tail = head;
                return;
            }
            next.pre = null;
            head = next;
            return;
        }
        if (next == null) {
            pre.next = null;
            tail = pre;
            return;
        }
        pre.next = next;
        next.pre = pre;

    }

    class Node {
        Node pre;
        Node next;
        int key;
        int val;

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

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

题目:https://leetcode-cn.com/problems/lru-cache/

推荐阅读