您的位置:首页 > 其它

使用队列的程序举例(1)

2018-04-03 20:40 211 查看
.h文件:/*循环队列的顺序存储*/

//初始化
void InitQueue(Queue &Q)
{
//把队首和队尾指针置为同一个下标值0表示队空
Q.front = Q.rear = 0;
}

//清空队列
void ClearQueue(Queue &Q)
{
Q.front = Q.rear = 0;
}

//检查队列是否为空
int QueueEmpty(Queue &Q)
{
return (Q.front == Q.rear);
}

//读取队首元素
ElemType QFront(Queue &Q)
{
if(Q.front == Q.rear)
{
cerr<<"Queue is empty!"<<endl;
exit(1);
}
return Q.queue[(Q.front+1) % QueueMaxSize];
//队首元素是队首指针的下一个位置中的元素
}

//检查队列是否已满
int QueueFull(Queue &Q)
{
return (Q.rear + 1) % QueueMaxSize == Q.front;
}

//插入元素
void QInsert(Queue &Q, const ElemType &item)
{
if(QueueFull(Q))
{
cerr<<"Queue overflow!"<<endl;
exit(1);
}
Q.rear = (Q.rear+1) % QueueMaxSize;
Q.queue[Q.rear] = item;
}

//删除元素
ElemType QDelete(Queue &Q)
{
if(QueueEmpty(Q))
{
cerr<<"Queue is empty!"<<endl;
exit(1);
}
Q.front = (Q.front + 1) % QueueMaxSize;
return Q.queue[Q.front];
}

.cpp文件:#include <iostream>
#include <stdlib.h>

using namespace std;

typedef int ElemType;

const int QueueMaxSize = 50;

struct Queue
{
ElemType queue[QueueMaxSize];
int front;
int rear;
};

#include "queue.h"

int main()
{
Queue q;
InitQueue(q);
for(int i = 0; i < 6; i++)
{
int x = rand() % 100;
int y = rand() % 100;
if(!QueueFull(q))
{
QInsert(q,x);
cout<<x<<"进队,";
}
if(!QueueFull(q))
{
QInsert(q,y);
cout<<y<<"进队";
}
cout<<endl;
cout<<QDelete(q)<<"出队"<<endl;
}
cout<<endl;
while(!QueueEmpty(q))
cout<<QDelete(q)<<"出队"<<endl;
return 0;
}


此程序使用一个长度为6的顺序队列,利用此队列保存由计算机产生的随机数。主函数中的fo:循环体共执行6次,每次执行时首先产生出两个100以内的随机整数,接着在队列未满时人队,然后进行一次出栈操作,在主函数的最后使队列中的所有元素依次出队。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: