链式队列

来源:互联网 发布:刑天seo 梦芭莎 编辑:程序博客网 时间:2024/06/05 07:19

链式队列:利用带尾指针的单链表实现


1、头文件(lqueue.h)

#pragma once//防止头文件重复引用typedef struct QNode{int data;struct QNode *next;}QNode;typedef struct HNode{QNode *front;//队头指针QNode *rear;//队尾指针}HNode,*PLQueue;//初始化void InitQueue(PLQueue pq);//入队bool Push(PLQueue pq,int val);//出队bool Pop(PLQueue pq,int *rtval);//判空bool IsEmpty(PLQueue pq);//获得队头bool GetTop(PLQueue pq,int *rtval);//摧毁void Destroy(PLQueue pq);


2、源文件(lqueue.cpp)

#include <stdio.h>#include <stdlib.h>#include <assert.h>#include "lqueue.h"//初始化void InitQueue(PLQueue pq){assert(pq != NULL);pq->front = NULL;pq->rear = NULL;}//入队bool Push(PLQueue pq,int val)//O(1){QNode *p = (QNode *)malloc(sizeof(QNode));p->data = val;p->next = NULL;if(pq->front == NULL)//判断队空if(IsEmpty(pq)){pq->front = p;pq->rear = p;}else{pq->rear->next = p;pq->rear = p;}return true;}//出队(获得队头并删除)bool Pop(PLQueue pq,int *rtval)//O(1){if(IsEmpty(pq)){return false;}QNode *p = pq->front->next;*rtval = p->data;pq->front = p->next;free(p); return true;}//判空bool IsEmpty(PLQueue pq){return pq->front == NULL;}//获得队头但不删除bool GetTop(PLQueue pq,int *rtval){if(IsEmpty(pq)){return false;}QNode *p = pq->front->next;*rtval = p->data;return true;}//摧毁void Destroy(PLQueue pq){while(pq->front){pq->rear = pq->front->next;free(pq->front);pq->front = pq->rear;}}


3、测试源文件(test.cpp)

#include <stdio.h>#include <vld.h>#include "lqueue.h"int main(){HNode p;InitQueue(&p);for(int i = 0; i < 10;i++){Push(&p,i);//入队}int tmp;while(!IsEmpty(&p)){Pop(&p,&tmp);//出队printf("%d\n",tmp);}Destroy(&p);//摧毁Destroy(&p);return 0;}