队列的基本操作(C语言)

时间:2025-02-19 13:44:28
#define _CRT_SECURE_NO_WARNINGS 1 #include<> #include<> #include<> typedef int DataType; typedef struct Node { DataType data; struct Node *next; }QNode; typedef struct Queue { QNode *head; QNode *tail; }Queue; void QueueInit(Queue *pq)//初始化 { assert(pq); pq->head = NULL; pq->tail = NULL; } void QueueDestory(Queue *pq)//销毁 { assert(pq); QNode *val = pq->head; while (pq->head != NULL) { pq->head->next; free(val); } } void QueuePush(Queue *pq, int x)//入队 { assert(pq); if (pq->head == NULL) { QNode *NewNode = (QNode *)malloc(sizeof(QNode)); NewNode->data = x; NewNode->next = NULL; pq->head = NewNode; pq->tail = NewNode; } else { QNode *NewNode = (QNode *)malloc(sizeof(QNode)); NewNode->data = x; NewNode->next = NULL; pq->tail->next = NewNode; pq->tail = NewNode; } } void QueuePop(Queue *pq)//出队 { assert(pq); QNode *val = pq->head; if (pq->head == pq->tail) { pq->head = NULL; pq->head = NULL; free(val); } else { pq->head = pq->head->next; free(val); } } DataType QueueHead(Queue *pq)//取队头元素 { assert(pq); assert(pq->head); return pq->head->data; } bool QueueEmpty(Queue *pq)//检测队列是否为空 { assert(pq); return pq->head !=NULL; } DataType QueueSize(Queue *pq)//计算队列中元素个数 { assert(pq); QNode *val = pq->head; int size = 0; while(val) { size++; val=val->next; } return size; } int main() { Queue q; QueueInit(&q); QueuePush(&q, 1); QueuePush(&q, 2); QueuePush(&q, 3); printf("队列中%d个元素\n",QueueSize(&q)); printf("元素%d出队\n", QueueHead(&q)); QueuePop(&q); printf("队列中%d个元素\n",QueueSize(&q)); printf("元素%d出队\n", QueueHead(&q)); QueuePop(&q); printf("队列中%d个元素\n",QueueSize(&q)); QueuePush(&q, 4); QueuePush(&q, 5); while (QueueEmpty(&q)) { printf("元素%d出队\n", QueueHead(&q)); QueuePop(&q); } QueueDestory(&q); printf("队列中%d个元素\n", QueueSize(&q)); return 0; }