【数据结构 02】队列

一、原理

队列通常是链表结构,只允许在一端进行数据插入,在另一端进行数据删除。

队列的特性是链式存储(随机增删)和先进先出(FIFO:First In First Out)。

队列的缺陷:

  1. 不支持随机访问
  2. 不支持随机增删
  3. 每个数据都需要维护一个指针,增大了空间资源消耗

二、Queue.h

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

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

typedef int DataType;

typedef struct Node
{
	DataType data;
	struct Node* next;
}Node;

typedef struct Queue
{
	Node* head;
	int size;
}Queue;

void Init(Queue* q)
{
	// 初始化创建一个空的头节点
	q->head = (Node*)malloc(sizeof(Node));
	q->head->next = NULL;
	q->size = 0;
}

int Empty(Queue* q)
{
	return q->size == 0;
}

void Push(Queue* q, DataType x)
{
	Node* node = (Node*)malloc(sizeof(Node));
	node->data = x;
	node->next = NULL;

	Node* cur = q->head;
	while (cur->next != NULL)
	{
		cur = cur->next;
	}

	cur->next = node;
	++q->size;
}

void Pop(Queue* q)
{
	if (Empty(q))
	{
		printf("队列为空,pop失败\n");
		return;
	}

	Node* cur = q->head->next;
	q->head->next = cur->next;
	
	free(cur);
	cur = NULL;
	--q->size;
}

DataType Front(Queue* q)
{
	if (Empty(q))
	{
		printf("队列为空,无队列首元素\n");
		return NULL;
	}

	return q->head->next->data;
}

void Destroy(Queue* q)
{
	while (!Empty(q))
	{
		Pop(q);
	}
	free(q->head);
	q->head = NULL;
	printf("队列销毁成功\n");
}

int Size(Queue* q)
{
	return q->size;
}

void Print(Queue* q)
{
	if (Empty(q))
	{
		printf("队列为空\n");
		return;
	}

	Node* cur = q->head->next;
	while (cur != NULL)
	{
		printf("%2d ", cur->data);
		cur = cur->next;
	}
	printf(",队列首元素:%2d,队列长度为:%d\n", Front(q), Size(q));
}

三、test.c

cpp 复制代码
#define _CRT_SECURE_NO_WARNINGS 1

#include "Queue.h"

int main()
{
	Queue q;
	Init(&q);
	Push(&q, 1);
	Push(&q, 3);
	Push(&q, 5);
	Push(&q, 7);
	Push(&q, 2);
	Push(&q, 4);
	Push(&q, 6);
	Push(&q, 8);
	Print(&q);

	Pop(&q);
	Pop(&q);
	Pop(&q);
	Print(&q);

	Push(&q, 9);
	Print(&q);

	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Pop(&q);
	Print(&q);

	Push(&q, 10);
	Push(&q, 20);
	Print(&q);
	Destroy(&q);
	Print(&q);
}
相关推荐
不吃洋葱.2 小时前
力扣448.找到数组中所有消失的元素
数据结构·算法·leetcode
昂子的博客3 小时前
热门面试题第15天|最大二叉树 合并二叉树 验证二叉搜索树 二叉搜索树中的搜索
java·数据结构·算法
扫地僧0095 小时前
【中大厂面试题】腾讯 后端 校招 最新面试题
java·数据结构·后端·算法·面试·排序算法
天天年年天天。6 小时前
在 Linux 或 Unix 系统中使用 pthread_create 创建新线程的步骤
linux·数据结构
大锦终9 小时前
【C++】模板进阶
c语言·开发语言·数据结构·c++
.YY001.10 小时前
关于数据结构B树部分的知识点,解题过程以及方法思路
数据结构
烁34711 小时前
每日一题(小白)暴力娱乐篇29
java·数据结构·算法·娱乐
rigidwill66612 小时前
LeetCode hot 100—最长回文子串
数据结构·c++·算法·leetcode·职场和发展
小林熬夜学编程12 小时前
【高阶数据结构】第二弹---图的深度解析:从基本概念到邻接矩阵的存储与操作
c语言·数据结构·c++·算法·深度优先·图论
小开不是小可爱14 小时前
leetcode_383. 赎金信_java
java·数据结构·算法·leetcode