23
代码如下:
#include <iostream>
#include <fstream>
using namespace std;
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef char QElemType;
typedef int Status;
typedef char SElemType;
// 队列的链式存储结构
typedef struct QNode {
QElemType data; //数据域
struct QNode *next; //指针域
}QNode, *QueuePtr;
typedef struct {
QueuePtr front; //队头指针
QueuePtr rear; //队为指针
}LinkQueue;
Status InitQueue(LinkQueue &Q) //构造一个空的队列
{
Q.front = Q.rear = new QNode; //生成头结点作为头结点,队头队尾指针指向此节点
Q.front->next = NULL; //头节点的指针设置为空
return OK;
}
// 链队的入队
Status EnQueue(LinkQueue &Q, QElemType e)
{
QueuePtr p; //
p = new QNode; //为入队元素分配节点空间,用指针P指向
p->next = NULL;
p->data = e; //将新结点的数据域赋值e
Q.rear->next = p; //将新节点插入队尾
Q.rear = p; //修改队尾指针
return OK;
}
// 链队的出队
Status DeQueue(LinkQueue &Q, QElemType &e)
{
QueuePtr p;
if(Q.front == Q.rear) // 队列为空
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(LinkQueue Q)
{
if(Q.rear !=Q.front)
return Q.front->next->data; //返回队头元素的值,队头指针不变
}
int main()
{
int choose, flag= 0;
LinkQueue Q;
QElemType e, j;
cout << "1,初始化队列, 2,入队, 3,读取队头元素" << endl;
cout << "4,出队, 0,退出系统" << endl;
choose = -1;
while(choose != 0)
{
cout << "请选择操作项:";
cin >> choose;
switch(choose){
case 1: //初始化
if(InitQueue(Q))
{
flag = 1;
cout << "链队初始化成功.\n";
}
else {
cout << "链队初始化失败.\n\n";
}
break;
case 2: { //入队
fstream file;
file.open("QNode.txt");
if(!file){
cout << "读取文件失败.\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 << "\n\n" <<endl;
} else
cout << "队列创建失败,请重新选择.\n" << endl;
file.close();
}
break;
case 3: //出队
if(flag != -1 && flag != 0)
{
cout << "对头元素为:\n" << GetHead(Q) << endl;
}
else
cout << "队列中无元素,请重新选择.\n\n";
break;
case 4: // 链队的出队
cout << "依次弹出的对头元素为:\n";
while(DeQueue(Q, e))
{
flag = -1;
cout << e << " ";
}
cout << endl << endl;
break;
}
}
return 0;
}
网友评论