赞
踩
队列的特点就是先进先出,后进后出。
- typedef int QueueDataType;
-
- typedef struct queue {
- QueueDataType val;
- struct queue* next;
- }Qnode;
-
- typedef struct Queue {
- Qnode* phead;//队头
- Qnode* ptail;//队尾
- int size;//队列中的有效数据
- }Queue;
- //初始化队
- void QueueInit(Queue* pq)
- {
- assert(pq);
- pq->phead = pq->ptail = NULL;
- pq->size = 0;
- }
- //入队
- void QueuePush(Queue* pq, QueueDataType x)
- {
- assert(pq);
- Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));
- if (newnode == NULL)
- {
- printf("malloc fail\n");
- exit(-1);
- }
- pq->size++;
- newnode->val = x;
- newnode->next = NULL;
- if (pq->phead == NULL)
- {
- pq->phead = pq->ptail = newnode;
- }
- else
- {
- pq->ptail->next = newnode;
- pq->ptail = newnode;
- }
- }
- //出队
- void QueuePop(Queue* pq) {
- assert(pq);
- Qnode* next = pq->phead->next;
- free(pq->phead);
- pq->size--;
- pq->phead = next;
- }
- //获取队首元素
- QueueDataType QueueFront(Queue* pq) {
- assert(pq);
- assert(pq->size > 0);
- assert(pq->phead);
- return pq->phead->val;
- }
- //获取队尾元素
- QueueDataType QueueBack(Queue* pq) {
- assert(pq);
- assert(pq->ptail);
- assert(pq->size > 0);
- return pq->ptail->val;
- }
- //获取队列有效个数
- int QueueSize(Queue* pq) {
- assert(pq);
- return pq->size;
- }
- //判断队列是否为空,为空返回1,非空返回0
- bool QueueEmpty(Queue* pq) {
- assert(pq);
- return pq->size == 0 ? 1 : 0;
- }
- //打印队列
- void QueuePrint(Queue* pq) {
- assert(pq);
- assert(pq->phead);
- while (!QueueEmpty(pq))
- {
- printf("%d\n", pq->phead->val);
- QueuePop(pq);
- }
- }
- //销毁队列
- void QueueDestory(Queue* pq) {
- assert(pq);
- Qnode* cur = pq->phead;
- while (cur) {
- Qnode* next = cur->next;
- free(cur);
- cur = next;
- }
- pq->phead = pq->ptail = NULL;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。