一、实验目的:
1.熟悉循环队列的类型定义和基本运算;
2.学会利用队列的特点来解决实际问题。
二、实验要求:
设从键盘输入一整数序列a1,a2,…,an,试编程实现:当ai<0时,ai进队;当ai>0时,将队首元素出队;当ai=0时,表示输入结束。最后输出队列中的所有元素。 要求: 1)采用循环队列存储结构; 2)有异常处理功能。
三、具体实现:
算法思路:先建立一个循环队列,用while循环接收用户输入。若值小于0,进队;若大于0,则队首元素出队;若等于零循环结束,并输出目前队列中的元素。
/*蓝多多 算法作业*/
#include "malloc.h"
#include"stdio.h"//蓝多多算法与数据结构实验四(一)队列
#include <iostream>//ldd最爱的VS2019
#include<iomanip>
using namespace std;
#define QueueSize 5
typedef int QElemType;
typedef struct QNode {
QElemType data[QueueSize];
int front;
int rear;
}SqQueue;
int EnQueue(SqQueue& q, QElemType i);
int DeQueue(SqQueue& p, QElemType& j);
int main()
{
int a;
QElemType b;
SqQueue qu; //定义队列
qu.rear = qu.front = 0;
while (1)
{
cout << "请输入一整数(输入负数进队,正数出队,0为结束标志):" << setw(12);
cin>>a;
if (a<0)
{
if (EnQueue(qu, a))
{
cout << " 队列已经满,不能入队" << endl;
}
}
else if (a>0)
{
if (DeQueue(qu, b))
{
cout << "队列为空,不能出队" << endl;
}
}
else
break;
}
cout << "队列中的所有元素为:" << endl;
int maxqueue;
maxqueue = (qu.rear - qu.front + QueueSize) % QueueSize;
if (maxqueue ==0)
{
cout<<"队列为空"<<endl;
}
else
{
for (int i = 0; i < maxqueue; i++)
{
cout <<qu.data[(qu.front + i) % QueueSize] << setw(6);
}
}
system("pause");
return 0;
}
int EnQueue(SqQueue &q, QElemType i)
{
if ((q.rear + 1)% QueueSize == q.front)//队列已满
{
return 1;
}
else
{
q.data[q.rear] = i;//i入队
q.rear =( q.rear + 1)% QueueSize;
return 0;
}
}
int DeQueue(SqQueue &p, QElemType &j)
{
if (p.rear == p.front)//队列为空
{
return 1;
}
else
{
j = p.data[p.front];//j出队
p.front = (p.front + 1)% QueueSize;
cout << "出队元素是:" << j << endl;
return 0;
}
}
四、运行结果: