Java_CircularQueue 循环队列分享
具体内容解释都在注释中了
QueueInterface接口类
public interface QueueInterface<T> {
public void enQueue(T element);
public T deQueue();
public T getHead();
public boolean isEmpty();
}
CircularQueue实现接口类
public class CircularQueue<T> implements QueueInterface<T> {
protected T[] queue;//存储队列元素的数组
private final static int QUEUE_SIZE = 100;//循环队列的最大容量
protected int front,rear;//声明队头和队尾
public CircularQueue(){
queue = (T[]) (new Object[QUEUE_SIZE]);//存储元素最多可以为100个
front=rear=0;
}
public T[] getQueue() {
return queue;
}
public void setQueue(T[] queue) {
this.queue = queue;
}
public static int getQueueSize() {
return QUEUE_SIZE;
}
public int getFront() {
return front;
}
public void setFront(int front) {
this.front = front;
}
public int getRear() {
return rear;
}
public void setRear(int rear) {
this.rear = rear;
}
@Override
public void enQueue(T element) {//用于表达入队的方法
if (front == (rear+1)%QUEUE_SIZE) {//先判断是否队满
throw new RuntimeException("队满");
}
rear = (rear+1) % QUEUE_SIZE;//让输入时构成循环
queue[rear] = element;//此时尾指针指向的元素为引入的element值
}
@Override
public T deQueue() {//用于表达出队的方法
if (isEmpty())//先判断是否为空队
throw new RuntimeException("队空");
front = (front+1)%QUEUE_SIZE;//让在输出时也构成循环
T head =queue[front];//定义一个T的变量来承载此时呀输出的元素内容
return head;//返回这个元素内容
}
@Override
public T getHead() {//用于表达取队头元素的方法
if (isEmpty())//先判断是否为空队
throw new RuntimeException("队空");
T headElement = queue[front+1];//获取头指针读到的元素
return headElement;//返回读到的元素
}
@Override
public boolean isEmpty() {//用于表达判空的方法
if (rear == front)//
return true;
return false;
}
}
class Shijian {//实践类
public static <Int> void main(String[] args) {
CircularQueue<Integer> xhdl = new CircularQueue<Integer>();//创建对象来初始队列
System.out.println("入队中");
xhdl.enQueue(1);
xhdl.enQueue(3);
xhdl.enQueue(5);
xhdl.enQueue(7);
xhdl.enQueue(9);
System.out.println();
System.out.println("从队头到队尾依次输出队列中所有元素");
Int[] num = (Int[]) xhdl.getQueue();
int i = xhdl.getFront();
int j = xhdl.getRear();
do {
if (i<j) {
System.out.println(num[i+1]);
}
i++;
}while (i<j);
System.out.println("出队两个元素并将元素输出");
System.out.println(xhdl.deQueue());
System.out.println(xhdl.deQueue());
System.out.println("此时再取队头元素并输出,即"+xhdl.getHead());
System.out.println("从队头到队尾输出剩余对内元素");
int p = xhdl.getFront()+1;
do {
System.out.println(num[p]);
p++;
}while (p<=j);
}
}
运行结果
以上就是本文全部内容,如果它对您有帮助,请您帮我点个赞,这对我真的很重要