从零实现数据结构第五集:队列的实现

队列的实现可以看成一种特殊的链表的实现,所以和链表的逻辑几乎一样,就不再过多讲述

声明部分queue.h:

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

typedef int QueueDataType ;
typedef struct QueueNode
{
	struct QueueNode* next;
	QueueDataType data;
}node;

typedef struct Queue
{
	node* head;
	node* tail;
}QE;


void QueueInit(QE* qu);
void QueueDestroy(QE* qu);
void QueuePush(QE* qu, QueueDataType x);
void QueuePop(QE* qu);
QueueDataType QueueFront(QE* qu);
int QueueSize(QE* qu);

实现部分queue.c:

初始化函数:

void QueueInit(QE* qu)
{
	assert(qu);
	qu->head = qu->tail = NULL;
}

销毁函数:

void QueueDestroy(QE* qu)
{
	assert(qu);
	node* cur = qu->head;
	while (cur)
	{
		node* del = cur;
		cur = cur->next;
		free(del);
	}
	qu->head = qu->tail = NULL;
}

入队函数:

void QueuePush(QE* qu, QueueDataType x)
{
	assert(qu);
	//这里的逻辑和链表的新增节点一样
	node* newnode = (node*)malloc(sizeof(node));
	if (newnode == NULL)
	{
		printf("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	//这里需要单独判断是否为空,如果为空就直接指向新节点
	if (qu->head == NULL)
	{
		qu->tail = qu->head = newnode;
	}
	else//队中有节点
	{
		qu->tail->next = newnode;
		qu->tail = newnode;
	}
}

出队函数:

void QueuePop(QE* qu)
{
	assert(qu);
	assert(qu->head != NULL);
	if (qu->head->next == NULL)//判断队中是否只有一个节点
	{
		free(qu->head);
		qu->tail = NULL;
		qu->head = NULL;
	}
	else
	{
		node* newhead = qu->head->next;
		free(qu->head);
		qu->head = newhead;//最后改变头指针指向
	}
}

获取对头元素函数:

QueueDataType QueueFront(QE* qu)
{
	assert(qu);
	assert(qu->head != NULL);
	return qu->head->data;
}

获取队大小函数:


int QueueSize(QE* qu)
{
	assert(qu);
	node* cur = qu->head;
	int count = 0;
	while (cur)
	{
		count++;
		cur = cur->next;
	}
	return count;
}

测试部分test.c:

#define _CRT_SECURE_NO_WARNINGS
#include "queue.h"



int main()
{
	QE queue;
	QueueInit(&queue);
	QueuePush(&queue, 1);
	QueuePush(&queue, 2);
	QueuePush(&queue, 3);
	while (queue.head != NULL)
	{
		printf("%d ", QueueFront(&queue));
		QueuePop(&queue);
	}
	QueueDestroy(&queue); // 销毁队列,释放内存
	return 0;
}

阿里嘎多!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值