1.队列的概念及结构
队列:
只允许一端插入数据,另一端删除数据的特殊线性表
先进先出FIFO(First In First Out)
入队列:
进行插入操作的一端称为队尾
出队列:
进行删除操作的一端称为队头
2. 队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低。
DFS---深度优先遍历 -- 递归/栈实现非递归
BFS---广度优先遍历 -- 队列
// 链式结构:表示队列
#pragma once
#include <stdlib.h>
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
typedef int QDatatype;
typedef struct QueueNode
{
QDatatype data;
struct QueueNode* next;
}QNode;
typedef struct Queue
{
QNode* phead;
QNode* ptail;
int size;
}Queue;
//初始化队列
void QueueInit(Queue* pq);
//队尾入队列
void QueuePush(Queue* pq , QDatatype x);
//队头出队列
void QueuePop(Queue* pq);
//获取队头元素
QDatatype QueueFront(Queue* pq);
//获取队尾元素
QDatatype QueueBack(Queue* pq);
//队列大小
int QueueSize(Queue* pq);
//判断队列是否为空
bool QueueEmpty(Queue* pq);
//销毁队列
void QueueDestory(Queue* pq);
#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 QueueDestory(Queue* pq)
{
QNode* cur = pq->phead ;
while (cur)
{
/*QNode* tmp = cur;
cur = cur->next;
free(tmp);*/
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
//队尾入队列
void QueuePush(Queue* pq, QDatatype x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc");
return;
}
newnode->data = x;
newnode->next = NULL;
if (pq->phead == NULL)//isEmpty
{
assert(pq->ptail==NULL);
pq->phead = newnode;
pq->ptail = newnode;
}
else
{
pq->ptail->next = newnode;
pq->ptail = newnode;
}
pq->size++;
}
//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
//return pq->phead == NULL && pq->ptail == NULL;
}
//队头出队列
void QueuePop(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));//assert(pq->phead != NULL);
//1、一个节点
//2、多个节点
if (pq->phead->next == NULL)//一个节点要注意ptail别弄成野指针
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else
{
Queue* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
//获取队头元素
QDatatype QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->phead->data;
}
//获取队尾元素
QDatatype QueueBack(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->ptail->data;
}
//队列大小
int QueueSize(Queue* pq)
{
assert(pq);
return pq->size;
}
//测试
#define _CRT_SECURE_NO_WARNINGS 1
#include "Queue.h"
void TestQueue()
{
Queue q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
//QueuePop(&q);
//QueuePop(&q);
//QueuePop(&q);
//while (!QueueEmpty(&q))
//{
// printf("%d ", QueueFront(&q));
//
// QueuePop(&q);
//}
printf("\n");
//printf("%d ", QueueFront(&q));
//printf("%d ", QueueSize(&q));
//QueuePop(&q);
printf("%d ", QueueBack(&q));
printf("%d ", QueueBack(&q));
printf("%d ", QueueBack(&q));
QueueDestory(&q);
}
int main()
{
TestQueue();
return 0;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。