数据结构-链队列的基本操作代码实现

#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;
}

实验样例

 

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜菜的大鹏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值