数据结构——队列

本文详细介绍了队列的数据结构,包括队列的定义、链表实现、接口函数(如初始化、销毁、入队、出队等)、队头队尾操作以及相关辅助函数,最后展示了队列在C语言中的使用示例。
摘要由CSDN通过智能技术生成

1.队列的基本结构

队列的特点为先进先出,属于线性结构,我们可以使用链表来实现。

队列
typedef int QDataType;
typedef struct QueueNode      //链表
{
	QDataType data;
	struct QueueNode* next;
}QNode;                       

typedef struct Queue
{	
	QNode* head;
	QNode* tail;
}Q;

2.队列的接口函数

初始化

void QueueInit(Q* pq);

void QueueInit(Q* pq)
{
	assert(pq);
	pq->head = NULL;
	pq->tail = NULL;
}
销毁

void QueueDestory(Q* pq);

void QueueDestory(Q* pq)
{
	assert(pq);
	QNode* cur = pq -> head,* tmp;
	while (cur != pq->tail&&cur)
	{
		tmp = cur->next;				
		free(cur);
		cur = tmp;
	}
	pq->head = pq->tail = NULL;
}
队尾入

void QueuePush(Q* pq, QDataType x);

void QueuePush(Q* pq, QDataType x)
{
	assert(pq);
	QNode* new = (QNode*)malloc(sizeof(QNode));
	if (new == NULL)
	{
		printf("malloc fail!");
		exit(-1);
	}
	else
	{
		new->data = x, new->next = NULL;
		if (pq->head == NULL)
		{
			pq->head = pq->tail = new;
		}
		else
		{
			pq->tail->next = new;
			pq->tail = new;
		}
	}	
}
队头出

void QueuePop(Q* pq);

void QueuePop(Q* pq)
{
	assert(pq);
	assert(pq->head);
	if (pq->head == pq->tail)
	{
		printf("%d ", QueueFront(pq));
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else 
	{
		QNode* tmp = pq->head->next;
		printf("%d ", QueueFront(pq));
		free(pq->head);
		pq->head = tmp;
	}	
}
队头

QDataType QueueFront(Q* pq);

QDataType QueueFront(Q* pq)
{
	assert(pq);
	assert(pq->head);
	return pq->head->data;
}
队尾

QDataType QueueBack(Q* pq);

QDataType QueueBack(Q* pq)
{
	assert(pq);
	assert(pq->tail);
	return pq->tail->data;
}
队列长度

int QueueSize(Q* pq);

int QueueSize(Q* pq)
{
	assert(pq);
	int i = 0;
	QNode* cur = pq->head;
	while (cur)
	{
		i++;
		cur = cur->next;
	}
	return i;
}
队列是否为空

bool QueueEmpty(Q* pq);

bool QueueEmpty(Q* pq)
{
	assert(pq);
	return pq->head == NULL;
}

3.队列的使用

int main()
{
	Q queue;
	QueueInit(&queue);
	QueuePush(&queue, 1);
	QueuePush(&queue, 2);
	QueuePush(&queue, 3);
	printf("\n%d ", QueueSize(&queue));
	QueuePop(&queue);
	QueuePop(&queue);
	QueuePop(&queue);	
	QueueDestory(&queue);
	return 0;
}

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值