队列特点
我们知道栈是先进后出;而队列是先进先出。
代码实现
.h文件
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct
{
QNode* head;
QNode* tail;
}Queue;
//初始化
void QueueInit(Queue* pq);
//销毁
void QueueDestroy(Queue* pq);
//放数据
void QueuePush(Queue* pq, QDataType x);
//删除
void QueuePop(Queue* pq);
//长度
int QueueSize(Queue* pq);
//取头
QDataType QueueFront(Queue* pq);
//取尾
QDataType QueueBack(Queue* pq);
//判断空
bool QueueEmpty(Queue* pq);
在这里我们可以明显看出我删除和取头的时候我并没有传二级指针或返回改变后的头项的地址。原因在于作者用来一个结构体(包含了头和尾两个结构体指针)避免了这个问题。(我们这样想,我们传一个结构体地址我们就可以改变结构体里面的内容了。)
两个.c文件
#include"queue.h"
//初始化
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
//销毁
void QueueDestroy(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
//放数据
void QueuePush(Queue* pq, QDataType x)
{
assert(pq);
//开辟空间
QNode* newnode = (QNode*)malloc(sizeof(QNode));
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;
}
}
//判断空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
//删除
void QueuePop(Queue* 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;
}
}
//取头
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;
}
//长度
int QueueSize(Queue* pq)
{
assert(pq);
QNode* cur = pq->head;
int count = 0;
while (cur)
{
++count;
cur = cur->next;
}
return count;
}
#include"queue.h"
void tectQueue()
{
Queue Q;
QueueInit(&Q);
QueuePush(&Q, 1);
QueuePush(&Q, 2);
QueuePush(&Q, 3);
QueuePush(&Q, 4);
printf("%d ", QueueFront(&Q));
QueuePop(&Q);
printf("%d ", QueueFront(&Q));
printf("\n打印\n");
while (!QueueEmpty(&Q))
{
printf("%d ", QueueFront(&Q));
QueuePop(&Q);
}
printf("\n");
QueueDestroy(&Q);
}
int main()
{
tectQueue();
return 0;
}
结果展示