标签:
package Queue; public class LRUQueue<T> { 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<num; 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<num; i++) { queue[i] = queue[i+1]; } queue[num-1] = value; } } /** * 出队列 * @param args */ public T pop() { T popValue = queue[0]; for(int i=0; i<num; i++) { queue[i] = queue[i+1]; } queue[num--] = null; return popValue; } /** * 打印队列信息 * @param args */ public void print() { for(int i=0; i<this.num; i++) { System.out.print(queue[i] + " "); } System.out.println(); } public static void main(String[] args) { LRUQueue<Integer> lru_q = new LRUQueue<Integer>(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(); } }
标签:
原文地址:http://blog.csdn.net/veson__/article/details/51346373