目录
队列:先进先出
一、基础设置
此处用链表来实现队列
第一个结构体定义的是结点(类似链表),第二个定义的是队列(包含头尾指针和大小)
typedef int QType;
typedef struct QueueNode
{
struct Queue* next;
QType data;
}QNode;
typedef struct Queue
{
QNode* tail;
QNode* head;
int size;
}Queue;
二、函数实现
1. 初始化
void QInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
pq->size = 0;
}
2. 入队出队
思路与前面的入栈出栈类似,不同的是栈是后进先出,队列是先进先出
void QPush(Queue* pq, QType x)
{
assert(pq);
QNode* tmp = (QNode*)malloc(sizeof(QNode));
if (tmp == NULL)
{
perror("malloc");
exit(-1);
}
tmp->data = x;
tmp->next = NULL;
if (pq->tail == NULL)
{
pq->head = pq->tail = tmp;
}
else
{
pq->tail->next = tmp;
pq->tail = tmp;
}
pq->size++;
}
void QPop(Queue* pq)
{
assert(pq);
assert(pq->size > 0);
QNode* next = pq->head->next;
QNode* cur = pq->head;
free(cur);
cur = NULL;
pq->head = next;
if (pq->head == NULL)
pq->tail = NULL;
pq->size--;
}
3. 获取队头队尾
因为我们定义了头尾指针,这个就很好操作了
QType QHead(Queue* pq)
{
assert(pq);
assert(pq->head);
return pq->head->data;
}
QType QTail(Queue* pq)
{
assert(pq);
assert(pq->tail);
return pq->tail->data;
}
4. 判断队空
bool QEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
}
5. 队列大小
int QSize(Queue* pq)
{
assert(pq);
return pq->size;
}
三、代码汇总
Queue.h
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <stdbool.h>
typedef int QType;
typedef struct QueueNode
{
struct Queue* next;
QType data;
}QNode;
typedef struct Queue
{
QNode* tail;
QNode* head;
int size;
}Queue;
void QInit(Queue* pq);
void QDestroy(Queue* pq);
void QPush(Queue* pq, QType x);
void QPop(Queue* pq);
QType QHead(Queue* pq);
QType QTail(Queue* pq);
bool QEmpty(Queue* pq);
int QSize(Queue* pq);
Queue.c
#include "Queue.h"
void QInit(Queue* pq)
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
pq->size = 0;
}
void QDestroy(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur != NULL)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->size = 0;
}
void QPush(Queue* pq, QType x)
{
assert(pq);
QNode* tmp = (QNode*)malloc(sizeof(QNode));
if (tmp == NULL)
{
perror("malloc");
exit(-1);
}
tmp->data = x;
tmp->next = NULL;
if (pq->tail == NULL)
{
pq->head = pq->tail = tmp;
}
else
{
pq->tail->next = tmp;
pq->tail = tmp;
}
pq->size++;
}
void QPop(Queue* pq)
{
assert(pq);
assert(pq->size > 0);
QNode* next = pq->head->next;
QNode* cur = pq->head;
free(cur);
cur = NULL;
pq->head = next;
if (pq->head == NULL)
pq->tail = NULL;
pq->size--;
}
QType QHead(Queue* pq)
{
assert(pq);
assert(pq->head);
return pq->head->data;
}
QType QTail(Queue* pq)
{
assert(pq);
assert(pq->tail);
return pq->tail->data;
}
bool QEmpty(Queue* pq)
{
assert(pq);
return pq->size == 0;
}
int QSize(Queue* pq)
{
assert(pq);
return pq->size;
}
如果有不懂的部分可以在评论区一起讨论,如果c语言的知识有要回顾的可以看我之前写过的文章