队列的链式存储(带头结点)

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
typedef struct LNode {
	ElemType data;
	struct LNode* next;
}LNode;
typedef struct {
	LNode* front, * rear;
}LinkQueue;
//初始化队列
void Init(LinkQueue &Q)
{
	Q.front = Q.rear = (LNode*)malloc(sizeof(LNode));//一定要连着写
	Q.front->next = NULL;
}
//判断队列是否为空
bool IsEmpty(LinkQueue Q)
{
	if (Q.front == Q.rear)
	{
		return true;
	}
	else
	{
		return false;
	}
}
//入队,尾插法
void EnQueue(LinkQueue& Q, ElemType x)
{
	LNode* s;
	s = (LNode*)malloc(sizeof(LNode));
	s->data = x;
	s->next = NULL;
	Q.rear->next = s;
	Q.rear = s;
}
//出队,头部删除法,因为队列是先进先出
bool DeQueue(LinkQueue& Q, ElemType& x)
{
	if (Q.front == Q.rear)
	{
		return false;
	}
	LNode* p;
	p = Q.front->next;//指向第一个结点
	x = p->data;
	Q.front->next = p->next;
	if (Q.rear == p)//如果要删除的是最后一个结点
	{
			Q.rear=Q.front;//修改尾指针,让rear指向头结点,队列再一次变成空队列
	}
	free(p);
	return true;

}
int main()
{
	LinkQueue Q;
	ElemType element;
	bool ret;
	Init(Q);
	IsEmpty(Q);
	EnQueue(Q, 3);
	EnQueue(Q, 4);
	EnQueue(Q, 5);
	EnQueue(Q, 6);
	EnQueue(Q, 7);
	ret=DeQueue(Q, element);
	if (ret)
	{
		printf("出队成功,元素值为%d\n", element);
	}
	else
	{
		printf("出队失败");
	}
	return 0;
}

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值