package Queue;
public class LRUQueue {
private T[] queue = null;
private int num; //队列中元素的个数
/**
* 指定大小构造队列
* @param capacity
*/
public LRUQueue(int capacity) {
this.num = 0;
queue = (T[]) new Object[capacity];
}
/**
* 判断队列是为空
*/
public boolean isEmpty() {
return num==0? true:false;
}
/**
* 判断队列是否已满
*/
public boolean isFull() {
return num==queue.length? true:false;
}
/**
* 查找某值在队列中的索引,没有则返回-1
*/
public int searchIndex(T value) {
for(int i=0; i
if(queue[i]==value)
return i;
}
return -1;
}
/**
* 进队列
*/
public void push(T value) {
int Vindex = this.searchIndex(value);
//队列中没有value
if(Vindex==-1) {
//判断队列是否满
boolean isfull = this.isFull();
if(isfull==false) {
queue[num++] = value;
}
//满
else {
this.pop();
queue[num++] = value;
}
}
//队列中有value
else {
T temp = queue[Vindex];
for(int i=Vindex; i
queue[i] = queue[i+1];
}
queue[num-1] = value;
}
}
/**
* 出队列
* @param args
*/
public T pop() {
T popValue = queue[0];
for(int i=0; i
queue[i] = queue[i+1];
}
queue[num--] = null;
return popValue;
}
/**
* 打印队列信息
* @param args
*/
public void print() {
for(int i=0; i
System.out.print(queue[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
LRUQueue lru_q = new LRUQueue(5);
lru_q.push(5);
lru_q.print();
lru_q.push(3);
lru_q.print();
lru_q.push(5);
lru_q.print();
lru_q.push(4);
lru_q.print();
lru_q.push(3);
lru_q.print();
}
}
LRU是Least Recently Used 近期最少使用算法。
LRU队列即把队列中最近最少使用的数据淘汰掉。