用单链表实现LRU算法

LRU的算法规则是当空间满时,将近期最少使用的数据删除掉,以释放空间。将近期一直活跃的数据保存着


package com.yillion.dtl.utils;

import java.util.List;

public class LinkedListData {
    private int length;  //定义链表的长度
    private Node head; //定义链表的头结点
    private final int DATALENGTH= 10;


    public  LinkedListData(){
        this.head = new Node();
        this.length = 0;
    }

    public  LinkedListData(T data,Node next){
        this.length = 0;
        this.head = new Node<>(data,next);
    }

    //从头部插入一个结点
    public void insertElementAtBegin(T data){
        Node preNode = head.getNext();
        head.setNext(new Node(data,preNode));
        this.length++;
    }

    //删除某个结点的下个结点
    public  void deleteNodeData(Node pre){
        Node tmp = pre.getNext();
       pre.setNext(tmp.getNext());
       tmp = null;
       length--;
    }

    //获取查找到元素的前一个结点
    public Node findProNode(T data){
        Node node = head;
        while (node.getNext() != null){
            Node next = node.getNext();
            Object data1 = next.getData();
            if(data.equals(data1)){
                return node;
            }
            node = node.getNext();
        }
        return  null;
    }

    //添加一个结点

    public void addNode(T data){
        Node proNode = findProNode(data);
        if(proNode != null){
            deleteNodeData(proNode);
           insertElementAtBegin(data);
        }else{
            if(length>=DATALENGTH){
                deleteElement(); //删除尾结点
            }
            insertElementAtBegin(data);//插入新的结点
        }
    }


    //删除尾结点
    public  void  deleteElement(){
            Node node = head;
            //说明链表为空
            if(node.getNext() == null){
                return ;
            }

            while (node.getNext().getNext() != null){
                node = node.getNext();
            }
        Node tmp = node.getNext();
            node.setNext(null);
            tmp =null;
            length--;
    }

















    private class  Node{
        T  data;
        Node next;

        public T getData() {
            return data;
        }

        public void setData(T data) {
            this.data = data;
        }

        public Node getNext() {
            return next;
        }

        public void setNext(Node next) {
            this.next = next;
        }

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }

        public Node() {
            this.next = null;
        }
    }
}

你可能感兴趣的:(用单链表实现LRU算法)