数据结构之队的实现

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前期准备

1.头文件

#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>

typedef int QDataType;

typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType data;
}QNode;

typedef struct Queue
{
	QNode* head;
	QNode* tail;
}Que;

//初始化
void QueueInit(Que* pq);
//销毁
void QueueDestory(Que* pq);
//入队
void QueuePush(Que* pq, QDataType x);
//出队
void QueuePop(Que* pq);
//队头元素
QDataType QueueFront(Que* pq);
//队尾元素
QDataType QueueBack(Que* pq);
//判空
bool QueueEmpty(Que* pq);
//队的长度
int QueueSize(Que* pq);

2.初始化

//初始化
void QueueInit(Que* pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;//置空
}

3.销毁

//销毁
void QueueDestory(Que* pq)
{
	assert(pq);
	QNode* cur = pq->head;
	while (cur)
	{
		QNode* next = cur->next;//保存下一个结点
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}

一、入队和出队

1.入队

//入队
void QueuePush(Que* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));//创建结点
	if (newnode == NULL)
	{
		printf("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	//队列为空
	if (pq->head == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else//不为空
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}

2.出队

//出队
void QueuePop(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(&pq));//判空
	//一个节点
	//多个节点
	if (pq->head->next ==NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QNode* next = pq->head->next;
		free(pq->head);
		pq->head = next;
	}

}

二、队头队尾元素、判空和队的长度

1.队头队尾元素

//队头元素
QDataType QueueFront(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(&pq));
	return pq->head->data;
}
//队尾元素
QDataType QueueBack(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(&pq));
	return pq->tail->data;
}

2.判空

//判空
bool QueueEmpty(Que* pq)
{
	assert(pq);
	return pq->head == NULL;
}

3.队的长度

//队的长度
int QueueSize(Que* pq)
{
	assert(pq);
	assert(!QueueEmpty(&pq));
	int size = 0;
	QNode* cur = pq->head;
	while (cur)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

三、队的实现

#include"Queue.h"
void test()
{
	Que q;
	QueueInit(&q);
	QueuePush(&q, 1);
	QueuePush(&q, 2);
	QueuePush(&q, 3);
	QueuePush(&q, 4);
	QueuePush(&q, 5);
	printf("%d\n", QueueSize(&q));
	while (!QueueEmpty(&q))
	{
		printf("%d ", QueueFront(&q));
		QueuePop(&q);
	}
	printf("\n");
	
	QueueDestory(&q);

}
int main()
{
	test();
	return 0;
}

在这里插入图片描述

总结

以上为队的实现的全部内容,之后将会来写二叉树,堆的结构。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值