单链表实现LRU算法 (算法)

模拟LinkedList

/**
 * @author damei
 * @Time 2020/2/29 08:34
 * @Description:
 */
public class LinkedList {
    Node list;
    int size; //链表有多少个节点

    public LinkedList(){
        size = 0;
    }
    //添加节点
    //在头部添加
    public void put(T data){
        Node head = list;
        Node curNode = new Node(data,list);
        list = curNode;
        size++;
    }
    public void put(int index,T data){
        checkPositionIndex(index);
        Node cur = list;
        Node head = list;
        for(int i=0;i=0&&index<=size)){
            throw new IndexOutOfBoundsException("index:"+index+",size:"+size);
        }
    }

    //删除节点
    //删除头部节点
    public T remove(){
        if(list!=null){
            Node node = list;
            list = list.next;
            node.next = null;//促进GC回收
            size--;
            return node.data;
        }
        return null;
    }
    public T remove(int index){
        checkPositionIndex(index);
        Node head = list;
        Node cur = list;
        for(int i=0;i

模拟Lru算法

/**
 * @author damei
 * @Time 2020/2/29 09:22
 * @Description:
 */
public class LruLinkedList extends LinkedList {
    int memory_size;//用于限定内存空间大小 ,也就是缓存的大小
    static final int DEFAULT_CAP = 5;
    public LruLinkedList(){
        memory_size = DEFAULT_CAP;
    }
    public LruLinkedList(int default_memory_size){
        memory_size = default_memory_size;
    }
    public void lruPut(T data){
       if(size>=memory_size){
           removerLast();
           put(data);
       }else{
           put(data);
       }
    }

    //LRU删除
    public T lruRemove(){
        return removerLast();
    }

    //LRU访问
    public T lruGet(int index){
        checkPositionIndex(index);
        Node node = list;
        Node pre = list;
        for(int i=0;i

你可能感兴趣的:(数据结构与算法)