数据结构:队列的链式存储结构及实现

声明:本博客参考《大话数据结构》书籍。

1、引入两个指针front和rear,其中front指向头结点,rear指向队尾结点,如下图所示

2、当队列为空时,front和rear都指向头结点,

 

3、出队操作时需注意,若链表除头结点外只剩下一个元素时,则需将rear指向头结点,

4、具体代码实现如下:

#include<iostream>
using namespace std;
typedef int QElemType;
typedef int Status;
#define MAXSIZE 10
#define true 1
#define false 0
typedef int QElemType;
typedef struct QNode  //结点结构
{
	QElemType data;
	struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
	QueuePtr front, rear;//队头、队尾指针
}LinkQueue;
//初始化
Status InitQueue(LinkQueue *Q)
{
	QueuePtr l = (QueuePtr)malloc(sizeof(QNode));//生成一个头结点
	l->next = NULL;
	Q->front = l;
	Q->rear = l;
	return true;
}
//插入元素e为Q的新的队列元素
Status EnQueue(LinkQueue *Q, QElemType e)
{
	QueuePtr s = (QueuePtr)malloc(sizeof(QNode));
	if (!s)
		exit(OVERFLOW);
	s->data = e;
	s->next = NULL;
	Q->rear->next = s;//将新结点赋值给原队尾结点的后继
	Q->rear = s;
	return true;
}
//出队操作
Status DeQueue(LinkQueue *Q, QElemType *e)
{
	QueuePtr p;//定义一个指针
	p = Q->front->next;//p指向欲删除的队头结点
	*e = p->data;//将欲删除的队头结点的值赋给e
	Q->front->next = p->next;
	while (p == Q->rear)//若队头就是队尾,则删除后将rear指向头结点
	{
		Q->rear = Q->front;
	}
	free(p);
	return true;
}
//遍历输出
Status TraverQueue(LinkQueue Q)
{
	while (Q.front != Q.rear)
	{
		cout << Q.front->next->data << " ";
		Q.front = Q.front->next;
	}
	cout << endl;
	return true;
}
int main()
{
	LinkQueue Q;
	InitQueue(&Q);//初始化
	for (int i = 0; i < MAXSIZE; i++)
	{
		EnQueue(&Q, i);//插入元素
	}
	TraverQueue(Q);//遍历输出
	int e;
	DeQueue(&Q,&e);//出队
	TraverQueue(Q);//遍历输出
	system("pause");
	return 0;
}

 本人是小白,如有错误,请指正,谢谢。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值