数据结构_队列(单链表形式)_C实现

队列:先进先出,队头出相当于头删,队尾出相当于尾插;

Queue.h
#pragma once

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

/*
队列,先进的先出,尾插头删,因此很适合单链表的优势;所以选择单链表来表达队列;
*/

//定义一个符合队列特点的单链表
typedef int QueueDatatype;
//定义节点
typedef struct QueueList {
	QueueDatatype data;
	struct QueueList* next;
}QNode;

//定义队列的头节点,尾节点
typedef struct Queue {
	QNode* head;
	QNode* tail;
}Queue;

//定义接口功能
//初始化
void init(Queue* qnode);
//销毁
void destory(Queue* pq);
//尾:入队列
void Qpush(Queue* pq , QueueDatatype x);
//头:出队列
void Qpop(Queue* pq);
//判断Emp
bool Emp(Queue* pq);
//打印
void display(Queue* pq);
//获取队头元素
QueueDatatype QueueFront(Queue* pq);
//获取队尾元素
QueueDatatype QueueBack(Queue* pq);
Queue.c
#include"Queue.h"

//初始化
void init(Queue* pq) {
	assert(pq);
	pq->head = pq->tail=NULL;
}
//销毁
void destory(Queue* pq) {
	assert(pq);
	QNode* cur = pq->head;
	//回收队列中的指针;
	while (cur)
	{
		QNode* curnexr = cur->next;
		free(cur);
		cur = curnexr;
	}
	//断开头尾联系,避免野指针问题
	pq->head = pq->tail = NULL;
}

//入队列
void Qpush(Queue* pq, QueueDatatype x) {
	//定义一个节点接受入队参数,因此要为新节点开辟空间
	struct QueueList* node = (struct QueueList*)malloc(sizeof(struct QueueList));
	if (node == NULL)
	{
		printf("malloc failed\n");
		exit(-1);
	}
	node->data = x;
	node->next = NULL;
	//判断头节点状态
	if (pq->tail == NULL)
	{
		pq->tail = pq->head = node;
		return;
	}
	//连起来
	pq->tail->next = node;
	//移动尾节点
	pq->tail = node;
}

//判断Emp
bool Emp(Queue* pq) {
	assert(pq);
	return pq->tail == NULL;
}
//打印
void display(Queue* pq) {
	assert(pq);
	QNode* cur = pq->head;
	while (cur)
	{
		printf("%d ",cur->data);
		cur = cur->next;
	}
	printf("\n");
}
//头:出队列
void Qpop(Queue* pq) {
	assert(pq);
	//空队列
	assert(pq->head);
	//1个节点
	if (pq->head->next == NULL) {
		//内存释放,但是指针指向并没有变化
		free(pq->head);
		//因此需要置空,防止非法访问
		pq->head = pq->tail = NULL;
	}
	//多个节点
	else {
		QNode* cur = pq->head->next;
		//内存释放,但是指针指向并没有变化
		free(pq->head);
		//改变指向
		pq->head = cur;
	}
}
//获取队头元素
QueueDatatype QueueFront(Queue* pq) {
	assert(pq);
	//空队列则会空指针
	assert(pq->head);
	return pq->head->data;
}
//获取队尾元素
QueueDatatype QueueBack(Queue* pq) {
	assert(pq);
	//空队列则会空指针
	assert(pq->head);
	return pq->tail->data;
}
main.c
#include"stack.h"
#include"Queue.h"

void main() {
	Queue pq;
	init(&pq);
	printf("队列是否为空:%d \n", Emp(&pq));
	Qpush(&pq, 1);
	Qpush(&pq, 2);
	Qpush(&pq, 3);
	Qpush(&pq, 4);
	Qpush(&pq, 5);
	display(&pq);
	printf("队列是否为空:%d \n", Emp(&pq));
	Qpop(&pq);
	display(&pq);
	printf("队头元素为:%d \n", QueueFront(&pq)); 
	printf("队尾元素为:%d \n", QueueBack(&pq));

}

运行后结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值