typedef int Qelemtype;
#define OK 1
#define ERROR 0
#include<iostream>
using namespace std;
typedef struct QNode{
Qelemtype data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int InitQueue(LinkQueue &Q)//构造空队列Q
{
Q.front=Q.rear=(QueuePtr)malloc(sizeof(QNode));
Q.front->next=NULL;
return OK;
}
int DestroyQueue(LinkQueue &Q)//销毁队列Q
{
while(Q.front)
{
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear;
}
return OK;
}
int Enqueue(LinkQueue &Q,Qelemtype e)//在队尾插入元素e
{
QueuePtr L;
L=(QueuePtr)malloc(sizeof(QNode));
L->data=e;
L->next=NULL;
Q.rear->next=L;
Q.rear=L;
return OK;
}
int Dequeue(LinkQueue &Q,Qelemtype &e)//将队首元素删除,并用e返回其值
{
if(Q.front==Q.rear) return ERROR;
QueuePtr L;
L=Q.front->next;
e=L->data;
Q.front->next=L->next;
if(L==Q.rear) Q.rear=Q.front;
free(L);
return OK;
}
int Clearqueue(LinkQueue &Q)//清空队列
{
while(Q.front!=Q.rear)
{
QueuePtr L;
L=Q.front;
Q.front=Q.front->next;
free(L);
}
return OK;
}
int Queueempty(LinkQueue &Q)//判断队列是否为空
{
if(Q.front==Q.rear)return OK;
else return ERROR;
}
int main(){
LinkQueue Q;
InitQueue(Q);
cout<<"请输入入队的元素个数";
int j;
cin>>j;
for(int i=0;i<j;i++ )
{
int q;
cout<<"输入元素"<<i+1<<":";
cin>>q;
Enqueue(Q,q);
}
cout<<"出队:"<<endl;
for(i=0;i<j;i++)
{
int e;
Dequeue(Q,e);
cout<<e<<" ";
}
cout<<endl<<"清空队列"<<endl;
Clearqueue(Q);
if((Queueempty)(Q))
{cout<<"已经清空。。。。"<<endl;}
else cout<<"清空失败"<<endl;
cout<<"销毁队列"<<endl;
DestroyQueue(Q);
return OK;
}