LRU算法

Node节点定义 

package com.example.demo;

public class Node {
    Object key;
    Object value;
    Node pre;
    Node next;
    public Node(Object key, Object value) {
        this.key = key;
        this.value = value;
    }
}

LRU算法

package com.example.demo;

import java.util.HashMap;

public class Lru {
    private int currentSize;
    private int capcity;
    private HashMap caches;
    private Node first;
    private Node last;
    public Lru(int size) {
        currentSize = 0;
        this.capcity = size;
        caches = new HashMap(size);
    }
    public void put(K key, V value) {
        Node node = caches.get(key);
        if(node == null) {
            if(caches.size()>=capcity) {
                caches.remove(last.key);
                removeLast();
            }
            node = new Node(key,value);
            caches.put(key,node);
            currentSize++;
        }else {
            node.value = value;
        }
        moveToHead(node);
    }

    public Object get(K key) {
        Node node = caches.get(key);
        if(node == null) {
            return null;
        }
        moveToHead(node);
        return node.value;
    }

    private void moveToHead(Node node) {
        if (first == node) {
            return;
        }
        if(node.next != null) {
            node.next.pre = node.pre;
        }
        if(node.pre !=null) {
            node.pre.next = node.next;
        }
        if(node == last) {
            last = node.pre;
        }
        if(first == null || last == null) {
            first = last = node;
            return;
        }
        node.next = first;
        first.pre = node;
        first = node;
        first.pre = null;
    }
    /**
     * 移除最后一个节点
     */
  private void removeLast() {
        if (last != null) {
            if (last.pre != null) {
                last.pre.next = null;
            }else {
                first = null;
            }
            last = last.pre;
        }
    }
}

 

你可能感兴趣的:(算法,leetcode)