队列的链式存储结构——C实现

队列的链式存储结构。队列常用链表来实现,简称为链队列
本次设计的链队列有头结点,并且队首指向头结点,队尾指向链尾结点。
队列是先进先出的线性表,在队尾那一端插入元素,在队首那一端删除元素。

c语言代码:

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>

typedef char ElemType;
typedef struct Qnode
{
	ElemType data;
	struct Qnode *next;
}Qnode, *Qptr;     //定义节点

typedef struct LINKQUEUE
{
	Qptr front;
	Qptr rear;
}LinkQueue;       //定义队首、队尾指针

void InitQueue(LinkQueue *q) //初始化
{
	//定义头结点,队首队尾都指向头结点
	Qptr firstnode = (Qptr)malloc(sizeof(Qnode));
	q->front = q->rear = firstnode;
	if (!q->front)
	{
		exit(0);
	}
	q->front->next = NULL;
}

void PushQueue(LinkQueue *q, ElemType e) //插入
{
	//在队尾插入元素
	Qptr p = (Qptr)malloc(sizeof(Qnode));
	if (!p)
	{
		exit(0);
	}
	p->data = e;
	p->next = NULL;
	q->rear->next = p;
	q->rear = p;
}

void DetQueue(LinkQueue *q, ElemType &e) //出队列
{
	//出队列在队首进行
	if (q->front == q->rear)
	{
		printf("队列中无元素!\n");
		exit(0);
	}
	Qptr p = q->front->next;
	e = p->data;
	q->front->next = p->next;
	if (q->rear == p)
	{
		q->rear = q->front;
	}
	free(p);
}

void ClearQueue(LinkQueue *q) //清空队列
{
	while (q->front)
	{
		q->rear = q->front->next;
		free(q->front);
		q->front = q->rear;
	}
}

void DisplayQueue(LinkQueue *q) //显示队列
{
	if (q->front == q->rear)
	{
		printf("队列为空!\n");
	}
	else
	{
		Qptr p = q->front->next;
		while (p)
		{
			printf("%c ", p->data);
			p = p->next;
		}
		printf("\n");
	}
}

int main()
{
	ElemType c;
	int i;
	LinkQueue *q = (LinkQueue*)malloc(sizeof(LinkQueue));
	InitQueue(q);

	printf("请输入队列元素,元素之间用空格隔开,以“#”结束 \n");
	scanf("%c", &c);
	while (c != '#')
	{
		if (c != ' ')
		{
			PushQueue(q, c);
		}
		scanf("%c", &c);
	}
	c = getchar();//清除缓冲区
	printf("队列元素为:\n");
	DisplayQueue(q);

	printf("插入队列元素为: \n");
	scanf("%c", &c);
	PushQueue(q, c);
	printf("队列元素为:\n");
	DisplayQueue(q);

	printf("出队列次数: \n");
	scanf("%d", &i);
	for (int j = 0; j < i; j++)
	{
		DetQueue(q, c);
	}
	printf("队列元素为:\n");
	DisplayQueue(q);

	printf("销毁队列 \n");
	ClearQueue(q);
	DisplayQueue(q);

	system("pause");
	return 0;
}

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

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值