数据结构:链式存储结构的队列,链队列

数据结构:链式存储结构的队列,链队列
队列的链式存储结构是单链表,只能在尾部插入和在头部删除
头指针指向头节点,尾指针指向最后一个节点
空队列时,头指针和尾指针都指向头节点

#include <iostream>
using namespace std;
#define OK 1
#define ERROR 0
typedef int QElemType;
typedef int Status;

/* 节点结构 */
typedef struct QNode
{
	QElemType data;
	struct QNode *next;
}QNode,*Queueptr;
/* 链表结构 
 * 头指针指向头节点,尾指针指向最后一个节点
 * 链队列空的条件:front和rear都指向头节点
 */
typedef struct
{
	Queueptr front, rear;
}LinkQueue;

/* 链队列的初始化:InitQueue
 * 需要将front指向头节点
 * 初始还有输入带数据域的节点,则rear=front
 */
Status InitQueue(LinkQueue *Q, Queueptr p)
{
	Q->front = p;
	Q->rear = Q->front ;
	return OK;
}


/* 链队列入队操作:在链表尾部插入节点,EnQueue
 * 思路:
 * 1、新建一个节点s并初始化,并判断是否内存分配成功
 * 2、s->data=e;s->next=NULL;
 * 3、将原最后一个节点的next指向新节点:Q->rear->next=s;
 * 4、将rear指向新节点
 */
Status EnQueue(LinkQueue *Q, QElemType e)
{
	Queueptr s;
	s = (Queueptr)malloc(sizeof(QNode));
	if (!s)
	{
		cout << "内存分配不成功" << endl;
		return ERROR;
	}
	s->data = e;
	s->next = NULL;
	Q->rear->next = s;
	Q->rear = s;
	return OK;
}

/* 链队列出队操作:在链表头部删除第一个节点,DeQueue 
 * 思路:
 * 1、判断链队列是否为空:Q->front==Q->rear
 * 2、判断若只剩一个节点条件:Q->rear == p
 * 3、2成立:声明节点p,p=Q->front->next,e=p->data,Q->front->next=p->next,并将rear指向头节点,释放p
 * 3、2不成立:声明节点p,p=Q->front->next,e=p->data,Q->front->next=p->next,释放p
 * 4、综合2和3
 */
Status DeQueue(LinkQueue *Q, QElemType *e)
{
	if (Q->front == Q->rear)
	{
		cout << "链队列为空" << endl;
		return ERROR;
	}
	Queueptr p;
	p = Q->front->next;
	*e = p->data;
	Q->front->next = p->next;
	if (Q->rear == p)
	{
		Q->rear = Q->front;
	}
	free(p);
	return OK;
}

int main()
{
	int length;
	cout << "输入初始链队列长度:";
	cin >> length;
	cout << "在链队列中依次入队:";
	LinkQueue *Q;
	Queueptr p;
	Q = (LinkQueue *)malloc(sizeof(LinkQueue));
	p = (Queueptr)malloc(sizeof(QNode));
	InitQueue(Q,p);
	int i,e;
	for (i = 0; i < length; i++)
	{
		cin >> e;
		EnQueue(Q, e);
	}

	cout << "输出需要出队的元素个数:";
	cin >> length;
	cout << "出队元素依次为:";
	for (i = 0; i < length; i++)
	{
		DeQueue(Q, &e);
		cout << e << ' ';
	}
	cout << '\n';

	return OK;
}

结果为:
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CSU_hhxyliang

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

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

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

打赏作者

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

抵扣说明:

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

余额充值