# 146.LRU缓存

class ListNode {
  constructor(key, value) {
    this.key = key;
    this.value = value;
    this.next = null;
    this.prev = null;
  }
}

class LRUCache {
  constructor(max) {
    this.max = max; // 缓存最大数目
    this.hash = {}; // 哈希表
    this.count = 0; // 缓存数目
    this.dummyHead = new ListNode(); // 虚拟头结点
    this.dummyTail = new ListNode(); // 虚拟尾结点
    this.dummyHead.next = this.dummyTail;
    this.dummyTail.prev = this.dummyHead;
  }

  get(key) {
    let node = this.hash[key];
    if (!node) return -1;
    this.moveToHead(node);
    return node.value;
  }

  moveToHead(node) {
    this.removeFromList(node);
    this.addToHead(node);
  }
  removeFromList(node) {
    const prev = node.prev;
    const next = node.next;
    prev.next = node.next;
    next.prev = prev;
  }
  addToHead(node) {
    node.prev = this.dummyHead;
    node.next = this.dummyHead.next;
    this.dummyHead.next.prev = node; // 原来真实头节点的prev指向node
    this.dummyHead.next = node;
  }
  put(key, value) {
    let node = this.hash[key];

    // 不存在
    if (node === null) {
      if (this.count === this.max) {
        // 存储满了, 删除最远一次使用的数据
        this.removeLRUItem();
      }
      const newNode = new ListNode(key, value);
      this.hash[key] = newNode;
      this.addToHead(newNode);
      this.count++;
    } else {
      node.value = value; // 存在 更新value
      this.moveToHead(node); // 将数据更新到头部
    }
  }
  removeLRUItem() {
    const tail = this.popTail();
    delete this.hash[tail.key];
    this.count--;
  }
  popTail() {
    const tail = this.dummyTail.prev;
    this.removeFromList(tail);
    return tail;
  }
}
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
Last Updated: 6/27/2023, 7:40:45 PM