#include <iostream>
using 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<<p->data<<" ";
p=p->next;
}
return OK;
}
int main ()
{
int i,e;
int arr[5];
LinkQueue Q1; //定义指针
InitQueue(Q1); //构建空队列
cout<<"输入5个元素"<<endl; //输入队列
for(i=0;i<5;i++)
{
cin>>arr[i];
EnQueue(Q1,arr[i] );
}
cout<<"输出队列"<<endl;
PrintfQueue(Q1); //输出队列
cout<<endl;
cout<<"删除队头元素,"; //删除队列的队头元素,并用e返回其值
DeQueue(Q1, e);
cout<<"输出剩余队列"<<endl;
PrintfQueue( Q1);
cout<<endl;
cout<<"删除元素为"<<endl;
cout<<e<<endl;
DestroyQueue(Q1); //销毁队列
return 0;
}
数据结构-链式队列
最新推荐文章于 2021-12-26 23:26:43 发布