queue.h
#pragma once
#include <stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int QDatatype;
typedef struct QueueNode
{
struct QueueNode* next;
QDatatype data;
}QN;
typedef struct Queue
{
QN* head;
QN* tail;
int size;
}QU;
void QueueInit(QU* pq);
void QueueDestory(QU* pq);
void QueuePush(QU* pq,QDatatype x);
void QueuePop(QU* pq);
int QueueSize(QU* pq);
bool QueueEmpty(QU* pq);
QDatatype QueueFront(QU* pq);
QDatatype QueueBack(QU* pq);
queue.c
#include"queue.h"
void QueueInit(QU* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
pq->size = 0;
}
void QueueDestory(QU* pq)
{
assert(pq);
QN* cur = pq->head;
while (cur)
{
QN* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail;
pq->tail = 0;
}
void QueuePush(QU* pq, QDatatype x)
{
QN*newnode= (QN*)malloc(sizeof(QN));
if (newnode == NULL)
{
perror("malloc fail");
return;
}
newnode->data = x;
newnode->next = NULL;
if (pq->head == NULL)
{
assert(pq->tail == NULL);
pq->head = pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
pq->size++;
}
int QueueSize(QU* pq)
{
assert(pq);
return pq->size;
}
void QueuePop(QU* pq)
{
assert(pq);
assert(pq->head != NULL);
/*QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
if (pq->head == NULL)
pq->tail = NULL;*/
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QN* next = pq->head->next;
free(pq->head);
pq->head = next;
}
pq->size--;
}
bool QueueEmpty(QU* pq)
{
assert(pq);
return pq->size == 0;
}
QDatatype QueueFront(QU* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QDatatype QueueBack(QU* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
test.c
#include"queue.h"
void QueueTest01()
{
QU q;
QueueInit(&q);
QueuePush(&q, 1);
QueuePush(&q, 2);
QueuePush(&q, 3);
QueuePush(&q, 2);
QueuePush(&q, 7);
QueuePop(&q);
while (!QueueEmpty(&q))
{
printf("%d\n", QueueFront(&q));
QueuePop(&q);
}
printf("\n");
QueueDestory(&q);
}
int main(void)
{
QueueTest01();
return 0;
}