C++中队列有什么用

发布时间:2021-11-16 17:14:55 作者:小新
来源:亿速云 阅读:112

这篇文章主要介绍C++中队列有什么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1. 队列的概念及结构

队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头

C++中队列有什么用

C++中队列有什么用

2. 队列的实现

2.1 queue.h

#include<stdio.h>
#include<stdbool.h>
#include<assert.h>
#include<malloc.h>
typedef int QDataType;
typedef struct QueueNode
{
	struct QueueNode*next;
	QDataType data;
}QueueNode;
typedef struct Queue
{
	QueueNode *head;
	QueueNode *tail;
}Queue;
void QueueInit(Queue *pq);
void QueueDestory(Queue *pq);
void QueuePush(Queue *pq,QDataType x);
void QueuePop(Queue *pq);
QDataType QueueFront(Queue *pq);
QDataType QueueBack(Queue *pq);
bool QueueEmpty(Queue *pq);
int QueueSize(Queue *pq);

2.2 queue.c

#include"queue.h"
void QueueInit(Queue *pq)
{
	assert(pq);
	pq->head = pq->tail = NULL;
}
void QueueDestory(Queue *pq)
{
	assert(pq);
	QueueNode *cur = pq->head;
	while (cur)
	{
		QueueNode *next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = pq->tail = NULL;
}
void QueuePush(Queue *pq, QDataType x)
{
	assert(pq);
	QueueNode *newnode = (QueueNode*)malloc(sizeof(QueueNode));
	if (newnode == NULL)
	{
		printf("malloc fail\n");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pq->tail == NULL)
	{
		pq->head = pq->tail = newnode;
	}
	else
	{
		pq->tail->next = newnode;
		pq->tail = newnode;
	}
}
void QueuePop(Queue *pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	if (pq->head->next == NULL)
	{
		free(pq->head);
		pq->head = pq->tail = NULL;
	}
	else
	{
		QueueNode *next = pq->head->next;
		free(pq->head);
		pq->head = next;
	}
}
QDataType QueueFront(Queue *pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->head->data;
}
QDataType QueueBack(Queue *pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->tail->data;
}
bool QueueEmpty(Queue *pq)
{
	assert(pq);
	return pq->head == NULL;
}
int QueueSize(Queue *pq)
{
	int size = 0;
	QueueNode *cur = pq->head;
	while (cur)
	{
		QueueNode *next = cur->next;
		++size;
		cur = cur->next;
	}
	return size;
}

2.3 test.c

#include"queue.h"
void TestOne()
{
	Queue q;
	QueueInit(&q);
	QueuePush(&q, 1);
	QueuePush(&q, 2);
	QueuePush(&q, 3);
	QueuePush(&q, 4);
	while (!QueueEmpty(&q))
	{
		printf("%d  ", QueueFront(&q));
		QueuePop(&q);
	}
	printf("\n");
	QueueDestory(&q);
}
int main()
{
	TestOne();
	return 0;
}

以上是“C++中队列有什么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. 什么是JavaScript中队列
  2. JavaScript中队列有什么用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++如何实现数据结构的顺序表

下一篇:怎么从Chrome源码看浏览器进行layout布局

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》