【数据结构】 -- 队列

引入

队列是一种线性表,队列遵循先进先出的特性。先放入队列的数据,一定先出队列。

倘若数据以ABCD的顺序入队,出队的顺序一定也是ABCD。

队列的实现

队列要求先入先出,用数组实现要挪数据,效率非常低。双向链表实现非常方便但是占用内存比单链表多,所以在这里我们选择用单链表实现。

头文件:

#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>

typedef int QDataType;

typedef struct QueueNode
{
	struct QueueNode* next;
	QDataType val;
}QNode;

typedef struct Queue
{
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;


//队尾插入
void QueuePush(Queue* pq, QDataType x);

//队头删除
void QueuePop(Queue* pq);

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

//销毁
void QueueDestory(Queue* pq);

//显示数据个数
int QueueSize(Queue* pq);

//取队头
QDataType QueueFront(Queue* pq);

//取队尾
QDataType QueueBack(Queue* pq);

//判空
bool QueueEmpty(Queue* pq);

 这里的关键在于重新设置一个结构体Queue用来操作phead和ptaill,如果没有这个结构体,需要传入二级指针来实现,会更加复杂。同时Queue中的size还可以记录数据的个数;如果没有size需要计数器遍历链表才能得到链表的长度。

图示:

实现文件:

 

#define _CRT_SECURE_NO_WARNINGS 1

#include "Queue.h"


void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}


//队尾插入
void QueuePush(Queue* pq, QDataType x)
{
	//扩容
	QNode* newNode = (QNode*)malloc(sizeof(QNode));
	if (newNode == NULL)
	{
		perror("mailloc fail");
		exit(-1);
	}
	newNode->next = NULL;
	newNode->val = x;

	if (pq->ptail == NULL)
	{
		pq->phead = pq->ptail = newNode;
	}
	else
	{
		pq->ptail->next = newNode;
		pq->ptail = newNode;
	}
	pq->size++;

}


//显示数据个数
int QueueSize(Queue* pq)
{
	assert(pq);

	return pq->size;
}

//队头删除
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->size != 0);
	if (pq->phead = pq->ptail)//一个节点
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
		pq->size--;
	}
	else//多个节点
	{
		QNode* cmp = pq->phead;
		free(pq->phead);
		pq->phead = cmp;
		pq->size--;
	}
}

//取队头
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);

	return pq->phead->val;

}

//取队尾
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->ptail);

	return pq->ptail->val;
}



//判空
bool QueueEmpty(Queue* pq)
{
	assert(pq);
	
	return pq->size == 0;
}


//销毁
void QueueDestory(Queue* pq)
{
	assert(pq);

	QNode* cur = pq->phead;
	while (cur)
	{
		QNode* cmp = pq->phead->next;
		free(cur);
		cur = cmp;
		pq->size--;
	}
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

测试文件:

 

#define _CRT_SECURE_NO_WARNINGS 1
#include"Queue.h"


int main()
{
	Queue s;
	QueueInit(&s);
	QueuePush(&s, 1);
	QueuePush(&s, 2);
	QueuePush(&s, 3);

	int b = QueueFront(&s);
	QueuePush(&s, 4);
	
	QueuePop(&s);


	QueueDestory(&s);
	return 0;
}

  • 17
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值