Queue.c
1.頭文件的聲明
#include "Queue.h"
2.初始化和銷毀函數的定義
void QueueInit(Que* pq)
{
? ? assert(pq);
? ? pq->head = pq->tail = NULL;
? ? pq->size = 0;
}
void QueueDestroy(Que* pq)
{
? ? assert(pq);
? ? QNode* cur = pq->head;
? ? while (cur)
? ? {
? ? ? ? QNode* next = cur->next;
? ? ? ? free(cur);
? ? ? ? cur = next;
? ? }
? ? pq->head = pq->tail = NULL;
? ? pq->size = 0;
}
3.入隊列和出隊列函數的定義
void QueuePush(Que* pq, QDataType x)
{
? ? assert(pq);
? ? QNode* newnode = (QNode*)malloc(sizeof(QNode));
? ? if (newnode == NULL)
? ? {
? ? ? ? perror("malloc fail");
? ? ? ? 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;
? ? }
? ? pq->size++;
}
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;
? ? }
? ? pq->size--;
}
4.查找隊頭、查找隊尾函數的定義
//查找隊頭元素
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;
}
5.判空以及長度計算函數的定義
//判斷是否為空
bool QueueEmpty(Que* pq)
{
? ? assert(pq);
? ? return pq->head == NULL;
}
//長度計算
int QueueSize(Que* pq)
{
? ? assert(pq);
? ? return pq->size;
}
(3)Test.c
1.頭文件的聲明
#include "Queue.h"
2.測試函數的定義
void QueueTest() {
? ? Que pq;
? ? QueueInit(&pq);
? ? QueuePush(&pq, 1);
? ? QueuePush(&pq, 2);
? ? QueuePush(&pq, 3);
? ? QueuePush(&pq, 4);
? ? QueuePush(&pq, 5);
? ? while (!QueueEmpty(&pq)) {
? ? ? ? printf("%d ", QueueFront(&pq));
? ? ? ? QueuePop(&pq);
? ? }
? ? QueueDestroy(&pq);
}
?
?