提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
前期准备
1.头文件
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdbool.h>
#include<stdlib.h>
typedef int QDataType;
typedef struct QueueNode
{
struct QueueNode* next;
QDataType data;
}QNode;
typedef struct Queue
{
QNode* head;
QNode* tail;
}Que;
//初始化
void QueueInit(Que* pq);
//销毁
void QueueDestory(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);
2.初始化
//初始化
void QueueInit(Que* pq)
{
assert(pq);
pq->head = pq->tail = NULL;//置空
}
3.销毁
//销毁
void QueueDestory(Que* pq)
{
assert(pq);
QNode* cur = pq->head;
while (cur)
{
QNode* next = cur->next;//保存下一个结点
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
一、入队和出队
1.入队
//入队
void QueuePush(Que* pq, QDataType x)
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));//创建结点
if (newnode == NULL)
{
printf("malloc fail");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
//队列为空
if (pq->head == NULL)
{
pq->head = pq->tail = newnode;
}
else//不为空
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
2.出队
//出队
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;
}
}
二、队头队尾元素、判空和队的长度
1.队头队尾元素
//队头元素
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;
}
2.判空
//判空
bool QueueEmpty(Que* pq)
{
assert(pq);
return pq->head == NULL;
}
3.队的长度
//队的长度
int QueueSize(Que* pq)
{
assert(pq);
assert(!QueueEmpty(&pq));
int size = 0;
QNode* cur = pq->head;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
三、队的实现
#include"Queue.h"
void test()
{
Que q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 4);
QueuePush(&q, 5);
printf("%d\n", QueueSize(&q));
while (!QueueEmpty(&q))
{
printf("%d ", QueueFront(&q));
QueuePop(&q);
}
printf("\n");
QueueDestory(&q);
}
int main()
{
test();
return 0;
}
总结
以上为队的实现的全部内容,之后将会来写二叉树,堆的结构。