LRU算法实现(java手动实现)

package com.example.suanfa;

import java.util.HashMap;
import java.util.Map;

public class LRUCache<K, V> {

int capacity;

class Node {
    private Node pre;
    private Node next;
    private K key;
    private V val;

    public Node(K key, V val) {
        this.key = key;
        this.val = val;

    }

    public Node() {

    }

}

private Node head;
private Node tail;
Map<K, Node> map;

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

public V get(K key) {
    Node node = map.get(key);
    if (node == null) {
        //为空则添加,相当于从数据库中查询数据,然后塞进cache中
        return put(key, (V) key);
    }
    //不为空,将该节点调至队头
    unlinkNode(node);
    addFirst(node);
    return node.val;
}

public V put(K key, V val) {
    Node node = new Node(key, val);
    addFirst(node);
    map.put(key, node);
    if (map.size() > capacity) {
        //需要删除队尾的节点
        Node delNode = removeLast();
        map.remove(delNode.key);
    }

    return node.val;
}

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

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

private Node removeLast() {
    Node node = tail.pre;
    tail.pre = node.pre;
    node.pre.next = tail;
    node.pre = null;
    node.next = null;
    return node;

}

public int getCapacity() {
    return map.size();
}

public int getMaxCapacity() {
    return capacity;
}

public void traverseCacheBuffer() {
    Node p = head;
    while (p != null) {
        if (p.val != null) {
            if (p.next != tail) {
                System.out.print(p.val + "-->");
            } else {
                System.out.print(p.val);
            }

        }
        p=p.next;
    }
    System.out.println();
}


public static void main(String[] args) {
    LRUCache<Integer, Integer> cache = new LRUCache<>(5);

    int array[] = {1, 2, 1, 3, 5, 6, 8, 9, 6, 1, 3, 4};

    for (int i = 0; i < array.length; i++) {
        System.out.println("val is:" + cache.get(array[i]) + "----------map size is:" + cache.getCapacity());

    }
    cache.traverseCacheBuffer();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值