队列:队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(back)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
队列的特性:先进先出
队列的基本实现
头文件:Queue.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <assert.h>
typedef int QUDataType;
typedef struct QueueNode
{
struct QueueNode* _next;
QUDataType _data;
}QueueNode;
typedef struct Queue
{
QueueNode* _front; // 队头
QueueNode* _back; // 队尾
}Queue;
//初始化
void QueueInit(Queue* pq);
//销毁
void QueueDestory(Queue* pq);
//申请一个节点
QueueNode* BuyQueueNode(QUDataType x);
//入队
void QueuePush(Queue* pq, QUDataType x);
//出队
void QueuePop(Queue* pq);
//访问队头元素
QUDataType QueueFront(Queue* pq);
//访问队尾元素
QUDataType QueueBack(Queue* pq);
//判空
int QueueEmpty(Queue* pq);
//队列的大小
int QueueSize(Queue* pq);
//打印
void QueuePrint(Queue* pq);
void TestQueue();
源文件:Queue.c
#include "Queue.h"
//初始化
void QueueInit(Queue* pq)
{
assert(pq);
pq->_back = pq->_front = NULL;
}
//销毁
void QueueDestory(Queue* pq)
{
QueueNode *next;
QueueNode *cur;
assert(pq);
cur = pq->_front;
while (cur)
{
next = cur->_next;
free(pq);
cur = next;
}
}
//申请一个节点
QueueNode* BuyQueueNode(QUDataType x)
{
QueueNode *ret = (QueueNode*)malloc(sizeof(QueueNode));
ret->_data = x;
ret->_next = NULL;
return ret;
}
//入队
void QueuePush(Queue* pq, QUDataType x)
{
assert(pq);
if (pq->_front == NULL)
{
pq->_front = pq->_back = BuyQueueNode(x);
}
else
{
pq->_back->_next = BuyQueueNode(x);
pq->_back = pq->_back->_next;
}
}
//出队
void QueuePop(Queue* pq)
{
QueueNode* next;
assert(pq);
//判断队头是否等于队尾
//如果等于,则free队头或队尾,并将其置空
//如果不等于,则释放队头,则队头等于他的next
if (pq->_back == pq->_front)
{
free(pq->_front);
pq->_back = NULL;
pq->_front = NULL;
}
else
{
next = pq->_front->_next;
free(pq->_front);
pq->_front = next;
}
}
//访问队头元素
QUDataType QueueFront(Queue* pq)
{
assert(pq);
return pq->_front->_data;
}
//访问队尾元素
QUDataType QueueBack(Queue* pq)
{
assert(pq);
return pq->_back->_data;
}
//判空
int QueueEmpty(Queue* pq)
{
assert(pq);
return pq->_back == NULL ? 0 : 1;
}
//队列的大小
int QueueSize(Queue* pq)
{
assert(pq);
QueueNode* ret;
int size = 0;
ret = pq->_front;
while (ret)
{
ret = ret->_next;
size++;
}
free(ret);
ret = NULL;
return size;
}
//打印
void QueuePrint(Queue* pq)
{
QueueNode*cur = pq->_front;
if (pq->_front->_data == 0)
{
printf("队列为空\n");
return;
}
while (cur)
{
printf("%d ", cur->_data);
cur = cur->_next;
}
printf("\n");
}
测试:test.c
#include "Queue.h"
void TestQueue()
{
Queue pq;
QueueInit(&pq);
printf("入队: ");
QueuePush(&pq, 1);
QueuePush(&pq, 2);
QueuePush(&pq, 3);
QueuePush(&pq, 4);
QueuePrint(&pq);
printf("出队: ");
QueuePop(&pq);
QueuePop(&pq);
QueuePrint(&pq);
QueueFront(&pq);
int front = QueueFront(&pq);
printf("队头元素为: %d\n", front);
QueueBack(&pq);
int back = QueueBack(&pq);
printf("队尾元素为: %d\n", back);
QueueDestory(&pq);
}
int main()
{
TestQueue();
system("pause");
return 0;
}