// 队列的链式存储结构
#include <iostream>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef char QElemType;
typedef char SElemType;
typedef int Status;
// 队列链式存储结构类型
typedef struct QNode {
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front; // 队头指针
QueuePtr rear; // 队尾指针
}LinkQueue;
// 初始化链队
Status Init_Queue(LinkQueue &Q) { // 构造空队列Q
Q.front = Q.rear = new QNode; // 生成新结点作为头结点,队头和队尾指针指向此结点
Q.rear->next = NULL; // 头结点的指针域设置为空
return OK;
}
// 入队
Status EnQueue(LinkQueue &Q, QElemType e) { // 插入元素e作为Q链队的新的队尾元素
QueuePtr p;
p = new QNode; // 为入队元素分配结点存储空间,用指针p指向它
p->data = e;
p->next = NULL;
Q.rear->next = p; // 将新结点插入到队尾1
Q.rear = p; // 修改队尾指针
return OK;
}
// 出队
Status DeQueue(LinkQueue &Q, QElemType &e) {
QueuePtr p;
if (Q.rear == Q.front)
return ERROR; // 若队列为空
p = Q.front->next; // p指向队头元素
e = p->data; // e保存队头元素的值
Q.front->next = p->next; // 修改头指针
if (Q.rear == p)
Q.rear = Q.front; // 最后一个元素被删除,队尾指针指向队头结点
delete p;
return OK;
}
// 获取队头元素
SElemType GetHead_Queue(LinkQueue Q) {
if (Q.front != Q.rear) // 队列非空
return Q.front->next->data; // 返回队头元素的值,队头指针不变
}
// 删除队列
void Del_Queue(LinkQueue *Q) {
Q.front->next = NULL;
Q.rear ->next = NULL;
Q.front = Q.rear = NULL;
Q = NULL;
}
int main()
{
int flag = 0, choose;
LinkQueue Q;
QElemType e, j;
cout << "1.初始化链队 2.入队 3.读取队头元素 4.出队 5.清空队列 0.退出\n\n\n\n";
choose = -1;
while (choose != 0)
{
cout << "请选择链队操作项[0-5]:";
cin >> choose;
switch(choose) {
case 1:
if (Init_Queue(Q)) {
flag = 1;
cout << "链队初始化成功." << endl << endl;
}
else
cout << "链队初始化失败." << endl << endl;
break;
case 2: {
fstream file;
file.open("QNode.txt");
if (!file) {
cout << "文件打开失败.\n\n\n";
exit(ERROR);
}
if (flag) {
flag = 1;
cout << "链队入队元素依次为:\n";
while (!file.eof()) {
file >> j;
if (file.fail())
break;
else
{
EnQueue(Q, j);
cout << j << " ";
}
}
cout << endl << endl;
}
else
cout << "链队未创建成功,请重检测.\n\n\n";
file.close();
}
break;
case 3:
if (flag != -1 && flag != 0)
cout << "链队队头元素为:" << GetHead_Queue(Q) << endl << endl;
else
cout << "链队中没有此数据元素" << endl << endl;
break;
case 4:
cout << "链队依次弹出的队头元素为:" << endl;
while (DeQueue(Q, e)) {
flag = -1;
cout << e << " ";
}
cout << endl << endl << endl;
break;
case 5:
Del_Queue(&Q);
if(!Q)
cout << "链队清空" << endl;
break;
}
}
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~
如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~
ps: 问答会员年卡【8折】购 ,限时加赠IT实体书,即可 享受50次 有问必答服务,了解详情>>>https://t.csdnimg.cn/RW5m