核心提示:数据结构之链式队列代码教程#include using namespace std;#defineOK 1#define ERROR 0#define OVERFLOW -1typedefint QE...
数据结构之链式队列代码教程
#includeusing namespace std; #define OK 1 #define ERROR 0 #define OVERFLOW -1 typedef int QElemType; typedef int Status; typedef struct QNode{ //定义队列(链表)结构体 QElemType data; struct QNode *next; }QNode,*Queueptr; typedef struct{ Queueptr front; //指向队头 Queueptr rear; //指向队尾 }LinkQueue; Status InitQueue(LinkQueue &Q){ //构造空队列 Q.front=Q.rear=(Queueptr)malloc(sizeof(QNode)); //申请空间,队头队尾指向空队列 if(!Q.front)exit (OVERFLOW); Q.front->next=NULL; return OK; } Status DestroyQueue(LinkQueue &Q){ //销毁队列 while(Q.front){ Q.rear=Q.front->next; free(Q.front); Q.front=Q.rear; } return OK; } Status EnQueue(LinkQueue &Q, QElemType e){ //插入元素e为队列Q的队尾 Queueptr p; p= (Queueptr)malloc(sizeof(QNode)); //申请空间 if(!p)exit (OVERFLOW); p->data = e; p->next=NULL; Q.rear->next=p; Q.rear=p; return OK; } Status DeQueue(LinkQueue &Q, QElemType &e){ // 删除队列的队头元素,并用e返回其值 Queueptr p; if(Q.rear==Q.front) //当空队列返回0 return ERROR; p=Q.front->next; e=p->data; Q.front->next=p->next; if(Q.rear==p) Q.rear=Q.front; free(p); return OK; } Status PrintfQueue(LinkQueue Q){ //输出队列元素 Queueptr p; p=Q.front->next; while(p!=NULL){ cout< data<<" "; p=p->next; } return OK; } int main () { int i,e; int arr[5]; LinkQueue Q1; //定义指针 InitQueue(Q1); //构建空队列 cout<<"输入5个元素"< >arr[i]; EnQueue(Q1,arr[i] ); } cout<<"输出队列"<