队列--顺序存储
#include<stdio.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20
typedef int QElemType;
typedef int Status;
typedef struct {
QElemType data[MAXSIZE];
int front;
int rear;
}Queue;
Status visit(QElemType e){
printf("%d ",e);
return OK;
}
Status InitQueue(Queue *Q){
Q->front = 0;
Q->rear = 0;
}
Status QueueEmpty(Queue Q){
//不要根据front和rear是否为0判断,因为可能是入队之后出队,front和rear都不为0
if(Q.front == Q.rear){
return TRUE;
}
return FALSE;
}
int QueueLength(Queue Q){
return Q.rear - Q.front;
}
Status EnQueue(Queue *Q,QElemType e){
if(Q->rear >= MAXSIZE ){
return ERROR;
}
Q->data[Q->rear++] = e;
return OK;
}
Status DeQueue(Queue *Q,QElemType *e){
if(Q->front == Q->rear){
return ERROR;
}
*e = Q->data[Q->front++];
return OK;
}
Status QueueTraverse(Queue Q){
if(Q.front == Q.rear){
return ERROR;
}
int i = Q.front;
while(i < Q.rear){
visit(Q.data[i++]);
}
printf("\n");
return OK;
}
int main(){
QElemType e;
Status i;
int j;
Queue Q;
i = InitQueue(&Q);
if(i){
printf("初始化成功\n");
} else {
printf("初始化失败\n");
}
printf("队列是否为空 %d \t 长度 %d\n",QueueEmpty(Q),QueueLength(Q));
for(j = 0; j < 25; j++){
EnQueue(&Q,j);
}
printf("队列是否为空 %d \t 长度 %d\n",QueueEmpty(Q),QueueLength(Q));
QueueTraverse(Q);
DeQueue(&Q,&e);
printf("出队元素是 %d\n",e);
printf("队列是否为空 %d \t 长度 %d\n",QueueEmpty(Q),QueueLength(Q));
QueueTraverse(Q);
return 0;
}
如需转载,请注明文章出处,谢谢!!!
浙公网安备 33010602011771号