Queue.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
typedef int QDataType;
typedef struct QListNode
{
QDataType data;
struct QueueNode *next;
}QueueNode;
typedef struct Queue
{
QueueNode *front;
QueueNode *tail;
}Queue;
void QueueInit(Queue *pq);
void QueueDestory(Queue *pq);
void QueuePush(Queue *pq,QDataType x);
void QueuePop(Queue *pq);
QDataType QueueFrontNode(Queue *pq);
QDataType QueueTailNode(Queue *pq);
int QueueSize(Queue *pq);
int QueueEmpty(Queue *pq);
Queue.c
#include "Queue.h"
#include <stdio.h>
#include <assert.h>
void QueueInit(Queue *pq)
{
assert(pq);
pq->front = pq->tail = NULL;
}
void QueueDestory(Queue *pq)
{
assert(pq);
QueueNode *cur = (QueueNode*)malloc(sizeof(QueueNode));
cur = pq->front->next;
while (cur != NULL)
{
free(pq->front);
pq->front = cur;
cur = cur->next;
}
pq->front = pq->tail = NULL;
}
void QueuePush(Queue *pq, QDataType x)
{
assert(pq);
QueueNode *tmp = (QueueNode *)malloc(sizeof(QueueNode));
tmp->data = x;
tmp->next = NULL;
if (pq->tail==NULL)
{
pq->front = pq->tail = tmp;
}
else
{
pq->tail->next = tmp;
pq->tail = tmp;
}
}
void QueuePop(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->tail == pq->front)
{
free(pq->front);
pq->front = pq->tail = NULL;
}
else
{
QueueNode *tmp = pq->front->next;
free(pq->front);
pq->front = tmp;
}
}
QDataType QueueFrontNode(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->front->data;
}
QDataType QueueTailNode(Queue *pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
int QueueSize(Queue *pq)
{
assert(pq);
QueueNode *tmp = pq->front;
int size = 0;
while (tmp != NULL)
{
size++;
tmp = tmp->next;
}
return size;
}
int QueueEmpty(Queue *pq)
{
assert(pq);
return pq->front == NULL ? 1 : 0;
}
Test.c
#include "Queue.h"
int main()
{
Queue q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
while (!QueueEmpty(&q))
{
int front = QueueFrontNode(&q);
printf("%d ", front);
QueuePop(&q);
}
printf("\n");
QueueDestory(&q);
return 0;
}
测试结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/475b97530a4b4a8987c5beae0d8c5f11.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzQ2NDg2MjQz,size_16,color_FFFFFF,t_70)