数据结构:队列

代码实现:

1.Queue.h

cpp 复制代码
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>

//定义队列结构
typedef int QDataType;
typedef struct QueueNode {
	QDataType data;
	struct QDataType* next;
}QueueNode;
typedef struct Queue
{
	QueueNode* phead;
	QueueNode* ptail;
	int size;//因为不好遍历,只好保存有效数据个数
}Queue;

//初始化
void QueueInit(Queue* pq);

// ⼊队列,队尾
void QueuePush(Queue* pq, QDataType x);
// 出队列,队头
void QueuePop(Queue* pq);
//队列判空
bool QueueEmpty(Queue* pq);
//取队头数据
QDataType QueueFront(Queue* pq);
//取队尾数据
QDataType QueueBack(Queue* pq);
//队列有效元素个数
int QueueSize(Queue* pq);
//销毁队列
void QueueDestroy(Queue* pq);

2.Queue.c

cpp 复制代码
#include "Queue.h"
//初始化
void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

// ⼊队列,队尾
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	//申请新节点
	QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		perror("malloc fail!");
		exit(1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->phead ==NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		//队列不为空
		pq->ptail->next = newnode;
		pq->ptail = pq->ptail->next;
	}
	pq->size++;
}
//队列判空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == NULL && pq->ptail == NULL;
}
// 出队列,队头
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	//只有一个结点的情况
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		//删除头元素 
		QueueNode* next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}
	pq->size--;
}

//取队头数据
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->phead->data;
}
//取队尾数据
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->ptail->data;
}
//队列有效元素个数
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}

//销毁队列
void QueueDestroy(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	QueueNode* pcur = pq->phead;
	while (pcur)
	{
		QueueNode* Next = pcur->next;
		free(pcur);
		pcur = Next;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

3.test.c

cpp 复制代码
#include "Queue.h"

void QueueTest01()
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q, 1);
	QueuePush(&q, 2);
	QueuePop(&q,1);
	printf("head:%d\n", QueueFront(&q));//2
	printf("tail:%d\n", QueueBack(&q));//2
	printf("size:%d\n", QueueSize(&q));//1
	//销毁
	QueueDestroy(&q);
}

int main()
{
	QueueTest01();
	return 0;
}
相关推荐
垠二1 小时前
L2-4 寻宝图
数据结构·算法
a_j583 小时前
算法与数据结构(环形链表)
数据结构·链表
tekin4 小时前
Python 高级数据结构操作全解析:从理论到实践
数据结构·python·集合set·高级数据结构·集合操作·队列操作·堆操作
居然有人6545 小时前
23贪心算法
数据结构·算法·贪心算法
重生之我是冯诺依曼6 小时前
数据结构绪论
数据结构
h^hh7 小时前
洛谷 P3405 [USACO16DEC] Cities and States S(详解)c++
开发语言·数据结构·c++·算法·哈希算法
重生之我要成为代码大佬7 小时前
Python天梯赛10分题-念数字、求整数段和、比较大小、计算阶乘和
开发语言·数据结构·python·算法
Dreams°1237 小时前
【透过 C++ 实现数据结构:链表、数组、树和图蕴含的逻辑深度解析】
开发语言·数据结构·c++·mysql
wanjiazhongqi8 小时前
链表和STL —— list 【复习笔记】
数据结构·c++·笔记·链表
Suk-god8 小时前
【Redis原理】底层数据结构 && 五种数据类型
数据结构·数据库·redis