本程序意在使用java类(初学)实现循环队列
具体原理请参考数据结构:队列
这里是方法
package pga;
public class MyQueue {
int MaxSize = 5;
private int[] date;
private int front;
private int rear;
public void GetFront(){
if(isEmpty())
System.out.println("This queue has no front");
else System.out.println(date[front]);
}
public boolean isFull(){
return (rear + 1) % MaxSize == front;
}
public boolean isEmpty(){
return front == rear;
}
public void InitQueue()
{
date = new int[MaxSize];
front = rear = 0;
}
public boolean EnQueue(int e)
{
if (isFull()) {
System.out.println("This queue is full");
return false;
}
date[rear] = e;
rear = (rear + 1) % MaxSize;
return true;
}
public boolean DeQueue()
{
if (isEmpty()){
System.out.println("This queue is empty");
return false;
}
front = (front + 1) % MaxSize;
return true;
}
}
这里是主程序
package pga;
public class app {
public static void main(String[] args){
MyQueue Q = new MyQueue();
Q.InitQueue();
Q.GetFront();//此时队列中没有元素
int[] list = {1, 2, 3, 4, 5};
for(int i : list)
Q.EnQueue(i);//前四个元素正常进队,录入第五个元素时队满
Q.GetFront();
Q.DeQueue();
Q.GetFront();
Q.DeQueue();
Q.DeQueue();
Q.DeQueue();//此时队空
Q.DeQueue();
// for(int i = 1;i <= 4;i++)
// Q.DeQueue();
Q.EnQueue(6);//测试循环队列是否正常
Q.GetFront();
}
}
注释已经写的很详细了,不做赘述。
下面是运行结果,请参考注释理解
来自石大ZJJ