#include<iostream>
using namespace std;
typedef struct Node
{
int data;
struct Node *next;
}QNode;
typedef struct
{
QNode *front;
QNode *rear;
}LinkQueue;
void creatQueue(LinkQueue &Q)
{
Q.front=Q.rear=new QNode;
Q.front->next=NULL;
return;
}
bool inQueue(LinkQueue &Q,int e)
{
QNode *cp;
cp=new QNode;
cp->data=e;
cp->next=NULL;
Q.rear->next=cp;
Q.rear=cp;
return true;
}
int outQueue(LinkQueue &Q)
{
float e;
QNode *cp;
if(Q.front==Q.rear)
return 0;
cp=Q.front->next;
e=cp->data;
Q.front->next=cp->next;
if(Q.rear==cp)
Q.rear=Q.front;
delete cp;
return e;
}
int getQueue(LinkQueue Q)
{
if(Q.front!=Q.rear)
return Q.front->next->data;
}
int lengthQueue(LinkQueue Q)
{
QNode *cp;
int i=0;
cp=Q.front;
while(cp!=Q.rear)
{
i++;
cp=cp->next;
}
return i;
}
void ouputQueue(LinkQueue Q)
{
QNode *cp;
cp=Q.front->next;
while(cp)
{
cout<<cp->data<<" ";
cp=cp->next;
}
cout<<endl;
return;
}
int main()
{
LinkQueue Q;
while(1)
{
cout<<"*****************************************************"<<endl;
cout<<"******1.链队列初始化 2.链队列元素填充********"<<endl;
cout<<"******3.链队列的长度 4.链队列的入队**********"<<endl;
cout<<"******5.链队列的出队 6.链队列的对头元素******"<<endl;
cout<<"******7.链队列的显示 8.退出程序 ***********"<<endl;
cout<<"输入你要执行的操作:";
int n;
int e;
int a=1;
int ch;
cin>>ch;
switch(ch)
{
case 1:
creatQueue(Q);
cout<<"链队列初始化成功!"<<endl;
continue;
case 2:
cout<<"输入你要填充元素的个数:";
cin>>n;
for(a;a<=n;a++)
{
cout<<"输入入队的第"<<a<<"个元素:";
cin>>e;
inQueue(Q,e);
}
cout<<"元素输入成功!"<<endl;
continue;
case 3:
cout<<"链队列的长度为:"<<lengthQueue(Q)<<endl;
continue;
case 4:
cout<<"输入你要入队的元素:";
cin>>e;
inQueue(Q,e);
cout<<"元素填充成功!"<<endl;
continue;
case 5:
cout<<"链队列出队的的元素值为:";
cout<<outQueue(Q)<<endl;
cout<<"元素出队成功!"<<endl;
continue;
case 6:
cout<<"链队列的对头元素为:";
cout<<getQueue(Q)<<endl;
continue;
case 7:
cout<<"链队列的显示如下:"<<endl;
ouputQueue(Q);
cout<<"显示完毕!"<<endl;
continue;
case 8:
cout<<"程序退出!"<<endl;
break;
}
break;
}
return 0;
}
改代码采用C++进行编译,定义函数进行数据结构中队列的相关操作。