队列的顺序表示与实现

来源:互联网 发布:道教有什么软件 编辑:程序博客网 时间:2024/05/17 04:53

#include <iostream>using namespace std;#define QElemType int#define OK 1#define FALSE 0#define TRUE 1#define ERROR 0// 循环队列,队列的顺序存储结构#define MAXQSIZE 100//最大队列长度typedef struct{QElemType *base;//初始化的动态分配存储空间int Front;//头指针,若队列不空,指向队列头元素int Rear;//尾指针,若队列不空,指向队列尾元素的下一个位置}SqQueue;//构造一个空队列Qint InitQueue(SqQueue &Q){Q.base = (QElemType *)malloc(MAXQSIZE*sizeof(QElemType));if(!Q.base)exit(OVERFLOW);Q.Front = Q.Rear = 0;return OK;}//插入元素e为Q的新的队列元素int EnQueue(SqQueue &Q,QElemType e){if((Q.Rear + 1) % MAXQSIZE == Q.Front)//队列满return ERROR;Q.base[Q.Rear] = e;Q.Rear = (Q.Rear + 1) % MAXQSIZE;return OK;}//输出队列Q中的元素void QueueTraverse(SqQueue Q){if(Q.Front == Q.Rear)cout << "队列为空" << endl;while(Q.Front != Q.Rear){cout << Q.base[Q.Front ]<<" ";Q.Front = (++Q.Front) % MAXQSIZE;}cout << endl;}//若队列为空,则返回TRUE //否则,返回FALSEint QueueEmpty(SqQueue Q){if(Q.Rear == Q.Front)return TRUE;elsereturn FALSE;}//得到队列Q的长度int QueueLength(SqQueue Q){int i = 0;while(Q.Front != Q.Rear){++i;++Q.Front;}return i;}//若队列不空,用e返回队头指针void GetHead(SqQueue Q,QElemType &e){if(Q.Front == Q.Rear)cout << "队列空!" <<endl;e = Q.base[Q.Front];}//若队列不空,则用e返回Q的队头元素void DeQueue(SqQueue &Q,QElemType &e){if(Q.Front == Q.Rear)cout << "队列空!" << endl;e = Q.base[Q.Front];Q.Front = (Q.Front+1) % MAXQSIZE;}//销毁队列Q,Q不再存在void DestroyQueue(SqQueue &Q){if(Q.Front != Q.Rear){free(Q.base);Q.Front++;}cout << "队列不再存在!"<< endl;}//将队列Q清为空队列void ClearQueue(SqQueue &Q){while(Q.Front != Q.Rear){Q.base[Q.Front] = NULL;Q.Front++;}Q.Front = Q.Rear = 0;}void main(){SqQueue Q;InitQueue(Q);QElemType a = 10;EnQueue(Q,a);QElemType b = 11;EnQueue(Q,b);QueueTraverse(Q);////cout << QueueEmpty(Q) << endl;//cout << QueueLength(Q) << endl;//QElemType c;//GetHead(Q,c);//cout << c << endl;//QElemType d;//DeQueue(Q,d);//cout << d << endl;//QueueTraverse(Q);//DestroyQueue(Q);//QueueTraverse(Q);ClearQueue(Q);//QueueTraverse(Q);system("pause");}