数据结构:队列

代码实现:

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;
}
相关推荐
Andrew_Xzw11 分钟前
复现OpenVLA:开源的视觉-语言-动作模型及原理详解
数据结构·c++·python·深度学习·算法·开源
_Power_Y26 分钟前
浙大数据结构:04-树5 Root of AVL Tree
数据结构·c++·算法
jingling5551 小时前
后端开发刷题 | 兑换零钱(动态规划)
java·开发语言·数据结构·算法·动态规划
搁浅小泽2 小时前
数据结构绪论
数据结构·算法
流殇2582 小时前
数据结构(6)哈希表和算法
数据结构·哈希算法·散列表
摆烂小白敲代码2 小时前
大一新生以此篇开启你的算法之路
c语言·数据结构·c++·人工智能·经验分享·算法
Cyan_RA94 小时前
C 408—《数据结构》算法题基础篇—链表(上)
java·数据结构·算法·链表·c·408·计算机考研
youyiketing4 小时前
排序链表(归并排序)
数据结构·链表
程序猿阿伟5 小时前
《C++位域:在复杂数据结构中的精准驾驭与风险规避》
开发语言·数据结构·c++
独領风萧5 小时前
数据结构之栈(数组实现)
c语言·数据结构