赞
踩
- #pragma once
-
- #include<stdio.h>
- #include<assert.h>
- #include<windows.h>
-
- typedef int QDataType;
-
- typedef struct QNode{
- QDataType data;
- struct QNode *pNext;
- }QNode;
-
- typedef struct Queue{
- QNode *pFront;//队列头
- QNode *pRear;//队列尾
- int size;
- }Queue;
-
- //初始化
- void QueueInit(Queue *pQ);
-
- //入队
- void QueuePush(Queue *pQ, QDataType data);
-
- //出队
- void QueuePop(Queue *pQ);
-
- //返回队首元素
- QDataType QueueFront(Queue *pQ);
-
- //判断队列是否为空
- int QueueIsEmpty(Queue *pQ);
-
- //返回队列元素个数
- int QueueSize(Queue *pQ);
-
- //销毁
- void QueueDestroy(Queue *pQ);
- #include "Queue.h"
-
- //初始化
- void QueueInit(Queue *pQ)
- {
- assert(pQ);
- pQ->pFront = pQ->pRear = NULL;
- pQ->size = 0;
- }
-
- //入队
- void QueuePush(Queue *pQ, QDataType data)
- {
- assert(pQ);
- pQ->size++;
- QNode *pNewNode = (QNode *)malloc(sizeof(QNode));
- assert(pNewNode);
-
- pNewNode->data = data;
- pNewNode->pNext = NULL;
-
- if (pQ->pRear == NULL){//空队列
- pQ->pFront = pQ->pRear = pNewNode;
- return;
- }
-
- //有元素队列
- pQ->pRear->pNext = pNewNode;
- pQ->pRear = pNewNode;
- }
-
- //出队
- void QueuePop(Queue *pQ)
- {
- assert(pQ);
- assert(pQ->size > 0);
- pQ->size--;
-
- //从对头出
- QNode *pOldFront = pQ->pFront;
- pQ->pFront = pQ->pFront->pNext;
- free(pOldFront);
-
- //只有一个元素的队列
- if (pQ->pFront == NULL){
- pQ->pRear = NULL;
- }
- }
-
- //返回队首元素
- QDataType QueueFront(Queue *pQ)
- {
- assert(pQ);
- assert(pQ->size > 0);
-
- return pQ->pFront->data;
- }
-
- //判断队列是否为空:1,空;0,不空
- int QueueIsEmpty(Queue *pQ)
- {
- return pQ->size == 0 ? 1 : 0;
- }
-
- //返回队列元素个数
- int QueueSize(Queue *pQ)
- {
- return pQ->size;
- }
-
- void QueueDestroy(Queue *pQ)
- {
- assert(pQ);
- QNode *queuePre = NULL;
- while (pQ->pFront){
- queuePre = pQ->pFront;
- pQ->pFront = pQ->pFront->pNext;
- free(queuePre);
- queuePre = NULL;
- }
- pQ->pRear = NULL;
- }
-
- void Queueprint(Queue *pQ)
- {
- assert(pQ);
- QNode *queue = pQ->pFront;
- while (queue){
- printf("%d->", queue->data);
- queue = queue->pNext;
- }
- printf("NULL\n");
- }
-
- int main()
- {
- Queue queue;
- QueueInit(&queue);
- QueuePush(&queue, 1);
- QueuePush(&queue, 2);
- QueuePush(&queue, 3);
- QueuePush(&queue, 4);
- QueuePush(&queue, 5);
- QueuePush(&queue, 6);
- Queueprint(&queue);
-
- QueuePop(&queue);
- Queueprint(&queue);
- QueuePop(&queue);
- Queueprint(&queue);
-
- printf("%d\n",QueueFront(&queue));
-
- QueueDestroy(&queue);
- Queueprint(&queue);
-
- system("pause");
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。