实验题目:循环队列的基本操作
• 【实验目的】
• 理解并掌握栈和队列的逻辑结构和存储结构;
• 理解栈和队列的相关基本运算;
• 编程对相关算法进行验证;
学会利用栈和队列解决实际问题
• 实验内容:编写一个程序,实现循环队列的各种基本运算,并在此基础上设计一个主程序完成如下功能:
• (1)初始化队列q;
• (2)判断队列q是否为空;
• (3)依次进队列元素-1,2,10;
• (4)出队一个元素,并输出该元素;
• (5)输出队列的长度(元素个数);
• (6)依次进队元素-3,12,10;
• (7)输出出队序列;
• (8)判断队列q是否为空。
头文件Queue.h
#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
#include <bits/stdc++.h>
using namespace std; //cout,cin
//函数结果状态代码
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define QElemType int
//OVERFLOW 在 math.h 中已定义为3
typedef int Status;
typedef int Boolean; // 布尔类型
//为了操作的方便,建议本书每一个程序都把c1.h包含进去
#define MAXQSIZE 100
typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue &Q);
int QueueLength(SqQueue Q);
Status EnQueue(SqQueue &Q,QElemType e);
Status DEQueue(SqQueue &Q,QElemType &e);
Status QueueEmpty(SqQueue &Q);
#endif // QUEUE_H_INCLUDED
Queue.cpp
#include "Queue.h"
#include <malloc.h>
#include <iostream>
using namespace std;
Status InitQueue(SqQueue &Q)
{
//构造一个空队列Q
Q.base = (QElemType * )malloc(MAXQSIZE *sizeof(QElemType));
if(!Q.base) exit (OVERFLOW);//存储空间分配失败
Q.front = Q.rear = 0;
return OK;
}
int QueueLength(SqQueue Q)
{
//返回Q的元素个数,即队列的长度
return(Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
Status EnQueue(SqQueue &Q,QElemType e)
{
//插入元素e为Q的新的对为元素
if((Q.rear + 1) % MAXQSIZE == Q.front)
return ERROR;//队列满
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
Status DEQueue(SqQueue &Q,QElemType &e)
{
//若队列不空,则删除Q的队头元素,用e返回其值,并返回OK;
//否则返回ERRPR
if(Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
Status QueueEmpty(SqQueue &Q)
{ //若队列Q为空队列,则返回TRUE,否则返回FALSE
if(Q.front==Q.rear) //队列空的标志
return TRUE;
else
return FALSE;
}
main.cpp
#include "Queue.h"
#include <iostream>
using namespace std;
int main()
{
SqQueue Q;
QElemType e;
cout << "①初始化队列Q:"<< endl;
InitQueue(Q);
cout << "②判断队列Q是否为空:"<< endl;
if(QueueEmpty(Q)) cout << "空"<< endl;
else cout << "不空"<< endl;
cout << "③依次进队列元素-1,2,10:";
EnQueue(Q,-1);
EnQueue(Q,2);
EnQueue(Q,10);
cout << endl;
cout << "④出队一个元素,并输出该元素:";
DEQueue(Q,e);cout << e <<endl;
cout << "⑤输出队列的长度:"<< QueueLength(Q)<< endl;
cout << "⑥依次进队元素-3,12,10:";
EnQueue(Q,-3);
EnQueue(Q,12);
EnQueue(Q,10);
cout << endl;
cout << "输出出队序列:";
for(int i = 1;i <= 5;i++)
{
DEQueue(Q,e);
cout << e << " ";
}
cout << endl;
cout << "判断队列是否为空:"<< endl;
if(QueueEmpty(Q)) cout << "空"<< endl;
else cout << "不空"<< endl;
return 0;
}