image.png
    image.png

    1. // 双向链表节点
    2. class LinkNode {
    3. public val: number;
    4. public key: number;
    5. public next: LinkNode | null;
    6. public front: LinkNode | null;
    7. constructor(key: number, val: number) {
    8. this.key = key;
    9. this.val = val;
    10. }
    11. }
    12. class LRUCache {
    13. public capacity: number; // 最大数量限制
    14. public map: Map<number, LinkNode>; //
    15. public head: LinkNode;
    16. public tail: LinkNode;
    17. constructor(capacity: number) {
    18. this.capacity = capacity;
    19. this.head = new LinkNode(0, 0);
    20. this.tail = new LinkNode(0, 0);
    21. this.map = new Map();
    22. // 默认head.next指向tail tail.front指向head
    23. this.head.next = this.tail;
    24. this.tail.front = this.head;
    25. }
    26. // 删除最后一个节点
    27. deleteLastNode(): void {
    28. const lastNode = this.tail.front;
    29. lastNode.front.next = this.tail;
    30. this.tail.front = lastNode.front;
    31. this.map.delete(lastNode.key);
    32. }
    33. // 移动节点到最前面
    34. moveNodeToTop(node: LinkNode): void {
    35. node.front.next = node.next;
    36. node.next.front = node.front;
    37. const temp = this.head.next;
    38. temp.front = node;
    39. node.next = temp;
    40. node.front = this.head;
    41. this.head.next = node;
    42. }
    43. get(key: number): number {
    44. if (this.map.has(key)) {
    45. const node = this.map.get(key);
    46. this.moveNodeToTop(node);
    47. return node.val;
    48. }
    49. return -1;
    50. }
    51. put(key: number, value: number): void {
    52. if (!this.map.has(key)) {
    53. if (this.map.size === this.capacity) {
    54. this.deleteLastNode();
    55. }
    56. const temp = this.head.next;
    57. const newNode = new LinkNode(key, value);
    58. this.head.next = newNode;
    59. newNode.front = this.head;
    60. newNode.next = temp;
    61. temp.front = newNode;
    62. this.map.set(key, newNode);
    63. } else {
    64. const node = this.map.get(key);
    65. node.val = value;
    66. this.moveNodeToTop(node);
    67. }
    68. }
    69. }