07.队列.顺序队列

来源:互联网 发布:上海网络教育学校排名 编辑:程序博客网 时间:2024/04/28 15:12

顺序队列

#include "stdio.h"    #include "stdlib.h"   #include "math.h"  #define OK 1#define ERROR 0#define TRUE 1#define FALSE 0#define MAXSIZE 20 /*存储空间初始分配量*/typedef int Status; typedef int QElemType; /*QElemType类型根据实际情况而定,这里假设为int*///循环队列的顺序存储结构typedef struct{QElemType data[MAXSIZE];int front;//头指针int rear;//尾指针,若队列不空,指向队列尾元素的下一个位置}SqQueue;/*初始化一个空队列Q*/Status InitQueue(SqQueue *Q){Q->front=Q->rear=0;return OK;}/*若队列Q为空队列,则返回TRUE,否则返回FALSE*/Status QueueEmpty(SqQueue Q){ if(Q.front==Q.rear)return TRUE;else return FALSE;}/*若队列未满,则插入元素e为Q新的队尾元素*/Status EnQueue(SqQueue *Q,QElemType e){if((Q->rear+1)%MAXSIZE == Q->front)//队列已满return ERROR;Q->data[Q->rear]=e;Q->rear=(Q->rear+1)%MAXSIZE;//rear指针向后移一位置,若到最后则转到数组头部return OK;}/*从队头到队尾依次对队列Q中每个元素输出*/Status QueueTraverse(SqQueue Q){ int i=Q.front;while(i!=Q.rear){printf("%d ",Q.data[i]);i=(i+1)%MAXSIZE;}printf("\n");return OK;}/*返回Q的元素个数,也就是队列的当前长度*/int QueueLength(SqQueue Q){return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;}/*若队列不空,则删除Q中队头元素,用e返回其值*/Status DeQueue(SqQueue *Q,QElemType *e){if(Q->front==Q->rear)//队列空return ERROR;*e=Q->data[Q->front];Q->front=(Q->front+1)%MAXSIZE;//front指针向后移一位置,若到最后则转到数组头部return OK;}/*若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR*/Status GetHead(SqQueue Q,QElemType *e){if(Q.front==Q.rear)//队列空return ERROR;*e=Q.data[Q.front];return OK;}/*将Q清为空队列*/Status ClearQueue(SqQueue *Q){Q->front=Q->rear=0;return OK;}int main(){Status j;int i=0,l;QElemType d;SqQueue q;InitQueue(&q);printf("初始化队列后,队列空否?%u(1:空 0:否)\n",QueueEmpty(q));printf("向队列中插入一些数据后: \n");do{d=i+100;if(d==-1)break;i++;EnQueue(&q,d);}while(i<MAXSIZE-1);QueueTraverse(q);printf("队列长度为: %d\n",QueueLength(q));printf("现在队列空否?%u(1:空 0:否)\n",QueueEmpty(q));printf("连续%d次由队头删除元素,队尾插入元素:\n",MAXSIZE);for(l=1;l<=MAXSIZE;l++){DeQueue(&q,&d);printf("删除的元素是%d,插入的元素:%d \n",d,l+1000);d=l+1000;EnQueue(&q,d);}l=QueueLength(q);printf("现在队列中的元素为: \n");QueueTraverse(q);j=GetHead(q,&d);if(j)printf("现在队头元素为: %d\n",d);ClearQueue(&q);printf("清空队列后, 队列空否?%u(1:空 0:否)\n",QueueEmpty(q));return 0;}


0 0
原创粉丝点击