java lru队列_LRU队列的实现

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队列即把队列中最近最少使用的数据淘汰掉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值