题目
在循环队列中设置一个循环队列flag,当flag=rear且flag=0时为队空,当flag=1,flag=rear时队满。请编写相应的入队和出队算法。(假设队头元素指向队头位置的前一个元素)。
static int QueueSize = 100;
static class CirQueue{
int[] data = new int[QueueSize];
int front,rear; //队头队尾指针
int flag;
public void Enqueue(int x);
public int DeQueue();
}
分析
- 队列的性质:先进先出,后进后出。
- 封装数组进行队列实现
- 循环队列
Java实现
static int QueueSize = 100;
static class CirQueue{
int[] data = new int[QueueSize];
int front,rear; //队头队尾指针
int flag;
public void Enqueue(int x){
if (flag != 1){
data[rear] = x;
if (rear+1 == QueueSize) rear = 0;
else rear++;
if (front == rear) flag = 1;
else flag = -1;
}
if (flag == 1){
System.out.println("队列以满");
}
}
public int DeQueue(){
if (flag != 0){
int num = data[front];
data[front] = 0;
if (front+1 == QueueSize) front = 0;
else front++;
if (front == rear) flag = 0;
else flag = -1;
return num;
}
if (flag == 0) {
System.out.println("队列以空");
}
return 0;
}
};
测试
public static void main(String[] args){
CirQueue queue = new CirQueue();
//入队测试
int k = 0;
while (queue.flag != 1) {
queue.Enqueue(k++);
System.out.println("头节点:"+queue.front);
System.out.println("尾节点:"+queue.rear);
}
//满队列测试
for (int i = 101; i < 110; i++) {
queue.Enqueue(i);
}
//出队测试
for (int i = 0; i < 10; i++) {
System.out.println("出队元素:"+queue.DeQueue());
System.out.println("头节点:"+queue.front);
System.out.println("尾节点:"+queue.rear);
}
//空队测试
for (int i = 0; i < 100 ; i++) {
System.out.println("出队元素:"+queue.DeQueue());
System.out.println("头节点:"+queue.front);
System.out.println("尾节点:"+queue.rear);
}
}
}