队列的概念及图解
队列:只允许在一端进行插入数据操作,在另一端进行数据删除操作的特殊线性表,队列具有先进先出FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾
出队列:进行删除操作的一端称为队头
队列的实现
定义部分
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int QDataType;
typedef struct QueueNode //队列的结构
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue //定义一个结构体存放队列的头尾结点和队列的长度
{
QNode* head;
QNode* tail;
int size;
}Que;
void QueueInit(Que* pq); //初始化队列
void QueueDestroy(Que* pq); //销毁队列
void QueuePush(Que* pq, QDataType x); //入队列
void QueuePop(Que* pq); //出队列
QDataType QueueFront(Que* pq); //查找队头值
QDataType QueueBack(Que* pq); //查找队尾值
bool QueueEmpty(Que* pq); //判断队列是否为空
int QueueSize(Que* pq); //队列长度
初始化队列
void QueueInit(Que* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
pq->size = 0;
}
销毁队列
void QueueDestroy(Que* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
pq->size = 0;
}
入队列
void QueuePush(Que* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc fail");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
if (pq->tail == NULL)
{
pq->head = newnode;
pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
pq->size++;
}
出对列
void QueuePop(Que* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
pq->size--;
}
查找队头值
QDataType QueueFront(Que* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
查找队尾值
QDataType QueueBack(Que* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
判断栈是否为空
bool QueueEmpty(Que* pq)
{
assert(pq);
return pq->head == NULL;
}
队列长度
int QueueSize(Que* pq)
{
assert(pq);
return pq->size;
}