实现LRU算法的两种方法

时间:2025-03-29 07:09:19
  • public class LRU {
  • static HashMap<Integer, Node> map = new HashMap<>();
  • static Node head = new Node();
  • static Node end = null;
  • static int capacity = 4;
  • public static void tranverse() { // 遍历链表
  • Node phead = ;
  • while (phead != null) {
  • ("(" + + "," + + ")->");
  • phead = ;
  • }
  • ();
  • }
  • public static int get(int key) {
  • if ((key)) {
  • Node node = (key);
  • remove(node);
  • setHead(node); // 访问结点时,将其置为头结点
  • return ;
  • }
  • return -1;
  • }
  • public static void remove(Node node) {
  • if (null == ) {
  • = null;
  • } else {
  • = ;
  • = ;
  • }
  • }
  • public static void setHead(Node node) {
  • if ( != null) {
  • = ;
  • = node;
  • = node;
  • = head;
  • } else {
  • = node;
  • = head;
  • }
  • }
  • public static void put(int key, int value) {
  • if ((key)) {
  • Node old = (key);
  • = value;
  • remove(old);
  • setHead(old);
  • } else {
  • Node newCode = new Node(key, value);
  • (key, newCode);
  • if ( != null) { // 找到end所在结点
  • end = ;
  • while ( != null) {
  • end = ;
  • }
  • }
  • if (() > capacity) // 当size >= capacity时移除end结点
  • if ( != -1) {
  • ();
  • remove(end);
  • setHead(newCode);
  • } else {
  • setHead(newCode);
  • }
  • } else {
  • setHead(newCode);
  • }
  • }
  • }
  • }
  • class Node { // 双向链表
  • int key = -1;
  • int value = -1;
  • Node pre = null;
  • Node next = null;
  • public Node() {
  • }
  • public Node(int key, int value) {
  • this.key = key;
  • this.value = value;
  • }
  • }