#include <iostream>
using namespace std;
typedef int ElemType;
typedef struct QNode {
ElemType data;
struct QNode* next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
bool InitQueue(LinkQueue& Q);//初始化链队列
bool EnQueue(LinkQueue& Q, ElemType e);//将元素e入队
bool DeQueue(LinkQueue& Q, ElemType& e);//将队首元素出队,并用元素e返回
bool DestroyQueue(LinkQueue& Q);//销毁队列
int QueueLength(LinkQueue Q);//返回队列长度
void TraverseQueue(LinkQueue Q);//遍历队列
void DisplyQueue(LinkQueue Q);//显示队列信息
bool InitQueue(LinkQueue& Q) {
Q.front = Q.rear = new QNode;//头节点
if (!Q.front || !Q.rear)return 0;
Q.front->next = NULL;
return 1;
}
bool EnQueue(LinkQueue& Q, ElemType e) {
QueuePtr temp = new QNode;
if (!temp)return 0;
temp->data = e;
temp->next = NULL;
Q.rear->next = temp;
Q.rear = temp;
return 1;
}
bool DeQueue(LinkQueue& Q, ElemType& e) {
if (Q.front == Q.rear)
return 0;
QueuePtr temp = Q.front->next;//指向第一个结点的指针
e = temp->data;
Q.front->next = temp->next;
if (Q.rear == temp)//若出队的是尾指针指向结点,则需要调整尾指针,否则删除后尾指针指向空
Q.rear = Q.front;
delete temp;
return 1;
}
bool DestroyQueue(LinkQueue& Q) {
QueuePtr temp = Q.front;
while (Q.front) {
Q.front = Q.front->next;
delete temp;
temp = Q.front;
}
return 1;
}
int QueueLength(LinkQueue Q) {
int n = 0;
while (Q.front != Q.rear) {
n++;
Q.front = Q.front->next;
}
return n;
}
void TraverseQueue(LinkQueue Q) {
if (Q.front->next) {
while (Q.front->next != Q.rear) {
cout << Q.front->next->data << " ";
Q.front = Q.front->next;
}
cout << Q.front->next->data << " ";
}
}
void DisplyQueue(LinkQueue Q)
{
int n = QueueLength(Q);
cout << "队列长度为" << n << endl;
if (n > 0) {
cout << "队列中元素为:";
TraverseQueue(Q);
cout << endl;
}
}
int main()
{
LinkQueue Q;
ElemType e;
int i;
if (InitQueue(Q))
cout << "初始化链队列成功" << endl;
else {
cout << "初始化链队列失败" << endl;
return 1;
}
cout << "请输入5个入队元素:" << endl;
for (i = 0; i < 5; i++) {
cin >> e;
EnQueue(Q, e);
}
DisplyQueue(Q);
cout << "出队4个元素" << endl;
for (i = 0; i < 4; i++)
DeQueue(Q, e);
DisplyQueue(Q);
cout << "请再输入1个入队元素:" << endl;
cin >> e;
EnQueue(Q, e);
DisplyQueue(Q);
cout << "出队1个元素" << endl;
DeQueue(Q, e);
DisplyQueue(Q);
cout << "出队1个元素" << endl;
DeQueue(Q, e);
DisplyQueue(Q);
DestroyQueue(Q);
cout << "队列已销毁" << endl;
return 0;
}
实验样例