以下是链队列的一些基本操作,包括链队列的入队、出队、读队头元素以及打印。
#include<iostream>
using namespace std;
//抽象数据类型
typedef int datatype;
typedef struct node
{
datatype data;
struct node *next;
}QueueNode;
typedef struct
{
QueueNode *front;
QueueNode *rear;
}LinkQueue;
//链队列的插入(入队)
void EnQueue(LinkQueue &QU,datatype x)
{
QueueNode *p=new QueueNode;
p->data=x;
p->next=NULL;
if(QU.front==NULL)
QU.front=QU.rear=p;
else
{
QU.rear->next=p;
QU.rear=p;
}
}
//链队列的删除(出队)
void DeQueue(LinkQueue &QU)
{
//参数检查
if(QU.front==NULL)
{
cout<<"列队为空(underflow)!"<<endl;
return;
}
else
{
QueueNode *q=QU.front;
QU.front=q->next;
delete q;
}
}
//读链队列的队头元素
datatype GetFront(LinkQueue &QU)
{
//参数检查
if(QU.front==NULL)
{
cout<<"列队为空(error)!"<<endl;
return 0;
}
return QU.front->data;
}
//打印链队列
void Print(LinkQueue &QU)
{
QueueNode *r=QU.front;
while(r!=NULL)
{
cout<<r->data<<" ";
r=r->next;
}
cout<<endl;
}
//主方法
int main()
{
LinkQueue QU;
QU.front=QU.rear=NULL;
datatype x;
cout<<"请输入要入队的元素,并以0为结尾:"<<endl;
while(cin>>x,x!=0)
EnQueue(QU,x);
cout<<"则队列中的元素为:"<<endl;
Print(QU);
cout<<"读取的对头元素为:"<<endl<<GetFront(QU)<<endl;
cout<<"一个元素出队之后的链队列为:"<<endl;
DeQueue(QU);
Print(QU);
return 0;
}