隊列的性質
一端進,從另一端出,先進的數據一定先出去,進數據的一端叫隊尾,出數據的一端叫隊頭
特點
保障公平性的排隊
#pragma once
#include<stdlib.h>
#include<stdbool.h>
#include<assert.h>typedef int QDataType;
typedef struct QueueNode
{int val;struct QueueNode* next;
}QNode;入隊列
//void QueuePush(QNode** pphead, QNode** pptail);
//出隊列
//void QueuePop(QNode** pphead, QNode** pptail);typedef struct Queue
{QNode* phead;QNode* ptail;int size;
}Queue;void QueueInit(Queue* pq);
void QueueDestroy(Queue* pq);// 入隊列
void QueuePush(Queue *pq, QDataType x);
// 出隊列
void QueuePop(Queue* pq);QDataType QueueFront(Queue* pq);
QDataType QueueBack(Queue* pq);
bool QueueEmpty(Queue* pq);
int QueueSize(Queue* pq);
void QueueInit(Queue* pq)
{assert(pq);pq->phead = NULL;pq->ptail = NULL;pq->size = 0;
}void QueueDestroy(Queue* pq)
{assert(pq);QNode* cur = pq->phead;while (cur){QNode* next = cur->next;free(cur);cur = next;}pq->phead = pq->ptail = NULL;pq->size = 0;
}// 入隊列
void QueuePush(Queue* pq, QDataType x)
{assert(pq);QNode* newnode = (QNode*)malloc(sizeof(QNode));if (newnode == NULL){perror("malloc fail");return;}newnode->val = x;newnode->next = NULL;if (pq->ptail){pq->ptail->next = newnode;pq->ptail = newnode;}else{pq->phead = pq->ptail = newnode;}pq->size++;
}// 出隊列
void QueuePop(Queue* pq)
{assert(pq);// 0個節點// 溫柔檢查//if (pq->phead == NULL)// return;// 暴力檢查 assert(pq->phead != NULL);// 一個節點// 多個節點if (pq->phead->next == NULL){free(pq->phead);pq->phead = pq->ptail = NULL;}else{QNode* next = pq->phead->next;free(pq->phead);pq->phead = next;}pq->size--;
}QDataType QueueFront(Queue* pq)
{assert(pq);// 暴力檢查 assert(pq->phead != NULL);return pq->phead->val;
}QDataType QueueBack(Queue* pq)
{assert(pq);// 暴力檢查 assert(pq->ptail != NULL);return pq->ptail->val;
}bool QueueEmpty(Queue* pq)
{assert(pq);return pq->size == 0;
}int QueueSize(Queue* pq)
{assert(pq);return pq->size;
}