// ConsoleApplication9.cpp : 此文件包含 'main' 函数。程序执行将在此处开始并结束。 /设计一个只能容纳有限个元素的 队列 类, 当队列 满 时,添加 元素,就抛出一个 队列满异常; 当队列 空 时,取出 元素,就抛出一个 队列空异常。 编写程序并测试队列类。 要求:使用动态数组存放队列元素/

#include using namespace std;

#define OK 0

typedef int QElmeType; typedef int Statue;

#define MAXQSIZE 6 typedef struct { QElmeType* base; //基地址,动态分配存储空间 int front; //头指针 int rear; //尾指针 }SqQueue;

//初始化队列 Statue InitQuene(SqQueue& Q) { Q.base = new QElmeType[MAXQSIZE]; //动态数组,为队列分配一个最大容量为MAXQSIZE的数组空间 if (Q.base == NULL) { exit(OVERFLOW); } //判断空间是否分配成功 Q.front = 0; Q.rear = 0; return OK; }

//入队操作(循环队列) Statue EnQueue(SqQueue& Q,int e) { if ((Q.rear + 1) % MAXQSIZE == Q.front) { //队列满,抛出异常 throw 'Queue is full!'; } Q.base[Q.rear] = e; //新元素插入队尾 Q.rear = (Q.rear + 1) % MAXQSIZE; //队尾指针向上移动 cout << Q.base[Q.front] << endl; return OK; }

//出队算法(循环队列) Statue DeQueue(SqQueue& Q, int& e) { if (Q.front == Q.rear) { //队列空,抛出异常 throw 'Queue is empty!'; } e = Q.base[Q.front]; //保存队头元素 Q.front = (Q.front + 1) % MAXQSIZE; //队头指针向上移动 return OK; }

void fun_EnQueue() { //当队列满时,添加元素,抛出一个队列满异常 SqQueue Q; InitQuene(Q); for (int i = 0;i < 6;i++) { try { EnQueue(Q, i); } catch (const char* msg) { //捕获队列满异常 cout << msg << endl; break; } } for (int i = 0;i < MAXQSIZE;i++) { //遍历队列 cout << Q.base[i] << endl; } }

/当队列 满 时, 添加 元素, 就抛出一个 队列满异常; 当队列 空 时, 取出 元素, 就抛出一个 队列空异常。/

int main() { fun_EnQueue(); SqQueue Q; InitQuene(Q); int e; try { DeQueue(Q, e); } catch (const char* msg) { //捕获队列空异常 cout << msg << endl; } return 0; }


原文地址: https://www.cveoy.top/t/topic/nBiy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录