#include <iostream>
using namespace std;
typedef int QElemType; // 定义队列元素类型为整型
#define ERROR 0
#define OK 1
// 定义队列结点结构体
typedef struct QNode {
QElemType data; // 数据域
struct QNode *next; // 指针域
} QNode, *QueuePtr;
// 定义链式队列结构体
typedef struct {
QueuePtr front; // 队头指针
QueuePtr rear; // 队尾指针
} LinkQueue;
// 初始化链队列
int InitQueue(LinkQueue &Q) {
Q.front = Q.rear = new QNode; // 创建头结点
if (!Q.front)
return ERROR;
Q.front->next = NULL;
return OK;
}
// 判断链队列是否为空
int QueueEmpty(LinkQueue Q) {
return (Q.front == Q.rear);
}
// 获取链队列的队头元素
int GetHead(LinkQueue Q, QElemType &e) {
if (Q.front == Q.rear)
return ERROR;
e = Q.front->next->data;
return OK;
}
// 链队列入队
int EnQueue(LinkQueue &Q, QElemType e) {
QueuePtr p;
p = new QNode;
if (!p)
return ERROR;
p->data = e;
p->next = NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
// 链队列出队
int DeQueue(LinkQueue &Q, QElemType &e) {
if (Q.front == Q.rear)
return ERROR;
QueuePtr p;
p = Q.front->next;
e = p->data;
Q.front->next = p->next;
if (Q.rear == p)
Q.rear = Q.front;
delete p;
return OK;
}
// 销毁链队列
int DestroyQueue(LinkQueue &Q) {
QueuePtr p;
while (Q.front) {
p = Q.front->next; // 保存下一个节点的指针
delete Q.front;
Q.front = p; // 更新队头指针
}
Q.rear = NULL; // 队尾指针置空
return OK;
}
int main() {
LinkQueue q;
QElemType e;
InitQueue(q);
if (QueueEmpty(q))
cout << "链队列为空" << endl;
else
cout << "链队列不为空" << endl;
cout << "请输入链队列内容:(输入-999结束输入)" << endl;
cin >> e;
while (e != -999) {
EnQueue(q, e);
cin >> e;
}
// DestroyQueue(q);
GetHead(q, e);
cout << "链队列的队头元素为: " << e << endl;
cout << "链队列依次出队:" << endl;
while (!QueueEmpty(q)) {
DeQueue(q, e);
cout << e << " ";
}
return 0;
}
数据结构:链队列
于 2024-04-28 09:27:18 首次发布