// 循环队列采用顺序存储,为了区分队头和队尾,从1号下标开始存储
// 队头队尾同时指向0号下标表示队空,队尾下标的下一个元素是队头的时候表示队满
// 可以设置front指向队头元素,rear指向队尾元素的下一个位置
// 或者设置front指向队头元素的下一个节点,rear指向队尾元素
// 本程序采用前一种,后一种在操作的时候略有不便
// 出队的时候front+1,入队的时候rear+1
/*补充求队长*/
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 6
typedef struct node{
int data[MAXSIZE]; // 0号下标的元素空出来作为头节点
int front,rear;
}Queue;
void initQueue(Queue *Q){
Q->front=0;
Q->rear=0;
}
int isEmpty(Queue *Q){
if(Q->front==Q->rear)
return 1;
return 0;
}
int isFull(Queue *Q){
if(Q->front==(Q->rear+1)%MAXSIZE) return 1;
return 0;
}
int enQueue(Queue *Q, int e){
if(isFull(Q)){
return 0; // 判满
puts("Full!");
}
Q->rear=(Q->rear+1)%MAXSIZE;
Q->data[Q->rear]=e;
return 1;
}
int deQueue(Queue *Q,int *e){
if(isEmpty(Q)){
puts("Empty!");
return 0;
}
*e=Q->data[Q->front+1]; // +1跳过头节点
Q->front=(Q->front+1)%MAXSIZE;
return 1;
}
int QueueLength(Queue Q){
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
// 用idx暂时代替front,判断条件不变
void disp(Queue Q){
int idx=Q.front; // 未出队时,front默认为0
while(idx%MAXSIZE!=Q.rear){
printf("%d ",Q.data[++idx]);
}
}
int main(){
Queue Q;
initQueue(&Q);
enQueue(&Q,7);
enQueue(&Q,4);
enQueue(&Q,2);
enQueue(&Q,3);
enQueue(&Q,6);
int e;
deQueue(&Q,&e);
disp(Q); printf("\nLength:%d",QueueLength(Q));
printf("\ne:%d\n",e);
deQueue(&Q,&e);
deQueue(&Q,&e);
deQueue(&Q,&e);
deQueue(&Q,&e);
deQueue(&Q,&e); //Empty
}
3.3 循环队列
最新推荐文章于 2022-05-17 22:27:18 发布