public class LRU {
static int num=0;
//用链表实现一个LRU缓存(大小为100)中添加一个数据
public static Node addNewValue(Node head,Node x){
Node ptr=head;
num++;
//1.遍历链表查看数据是否已经存在
while(ptr!=null&&ptr.next.next!=null) {
//2.如果存在,删除当前结点,并在表头添加
if (ptr.next.value == x.value) {
ptr.next = ptr.next.next;
x.next = head;
head=x;
return head;
}
ptr=ptr.next;
num++;
}
//3.如果不存在
//a.缓存未满,直接在表头添加
if(num<100){
x.next=head;
head=x;
}
//b.缓存已满,删除表尾结点,在表头添加
else{
ptr.next=null;
x.next=head;
head=x;
}
return head;
}
//遍历链表(已知一个头结点,便可以遍历整个链表)
public static void printAll(Node head){
Node cur=head;
while (cur.next!=null){
System.out.print(cur.value+"->");
cur=cur.next;
}
System.out.print(cur.value);
System.out.println();
}
public static void main(String[] args) {
Node head1=new Node(3,null);
head1=new Node(3,head1);
head1=new Node(2,head1);
head1=new Node(1,head1);
printAll(head1);
Node x1=new Node(0);
printAll(addNewValue(head1,x1));
Node x2=new Node(2);
printAll(addNewValue(head1,x2));
}
}
class Node{
int value;
Node next;
public Node(int value) {
this.value = value;
}
public Node(int value,Node next){
this.value=value;
this.next=next;
}
}
运行结果截图: