
#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.front = Q.rear = new QNode;
Q.rear->next = NULL;
return OK;
}
Status EnQueue(LinkQueue &Q, QElemType e) {
QueuePtr p;
p = new QNode;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
Status DeQueue(LinkQueue &Q, QElemType &e) {
QueuePtr p;
if (Q.rear == Q.front)
return ERROR;
p = Q.front->next;
e = p->data;
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;
}
int main()
{
int flag = 0, choose;
LinkQueue Q;
QElemType e, j;
cout << "1.初始化链队 2.入队 3.读取队头元素 4.出队 0.退出\n\n\n\n";
choose = -1;
while (choose != 0)
{
cout << "请选择链队操作项[0-4]:";
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;
}
}
return 0;
}