#include<iostream>
using namespace std;
typedef struct LinkQueueNode//队列节点结构
{
int data;
LinkQueueNode *next;
}LQN,*LQNP;
typedef struct LinkQueue//链队列结构
{
LQNP front;//头结点指针(注意不是指向队头节点)
LQNP rear;//队尾节点指针
}LQ;
LQ CreateLinkQueue()//创建空队列
{
LQ Q;
Q.front=Q.rear=new LQN;//创建头结点
if(!Q.front)
cout<<"存储分配失败!"<<endl;
Q.front->next=NULL;
return Q;
}
LQ EnterQueue(LQ Q,int n)//元素n入队列
{
LQN *ptn;
ptn=new LQN;
ptn->next=NULL;
ptn->data=n;
Q.rear->next=ptn;
Q.rear=ptn;
return Q;
}
LQ OutQueue(LQ Q)//队头元素出队列
{
LQN *q;
q=Q.front->next;
Q.front->next=q->next;
delete q;
return Q;
}
int QueueLength(LQ Q)
{
int len=0;
LQN *p;
p=Q.front->next;
while(p)
{
len++;
p=p->next;
}
return len;
}
void PrintQueue(LQ Q)
{
LQN *p;
p=Q.front->next;
while(p!=Q.rear)
{
cout<<p->data<<"-->";
p=p->next;
}
cout<<p->data<<endl;
}
LQ EmptyQueue(LQ Q)
{
LQN *q,*p;
Q.rear=Q.front;
p=Q.front->next;
while(p)
{
q=p;
p=p->next;
delete q;
q=NULL;
}
return Q;
}
void DestroyQueue(LQ Q)
{
EmptyQueue(Q);
Q.rear=NULL;
delete Q.front;
}
int main()
{
LQ Q;
int choice,n;
Q=CreateLinkQueue();
if(Q.front)
cout<<"空队列创建成功!"<<endl;
while(1)
{
system("pause");
system("cls");
cout<<"1.元素入队列"<<endl;
cout<<"2.队头元素出队列"<<endl;
cout<<"3.打印队列元素"<<endl;
cout<<"4.清空队列"<<endl;
cout<<"0.退出程序"<<endl;
cout<<"请选择操作:";
cin>>choice;
switch(choice)
{
case 1:cout<<"输入入队列元素:";cin>>n;
Q=EnterQueue(Q,n);cout<<"元素成功入队列!"<<endl;break;
case 2:Q=OutQueue(Q);cout<<"队头元素已出队列!"<<endl;break;
case 3:cout<<"队列为:";PrintQueue(Q);break;
case 4:Q=EmptyQueue(Q);if(Q.front==Q.rear)cout<<"队列已清空!"<<endl;break;
case 0:DestroyQueue(Q);exit(0);
}
}
return 0;
}