//链队列的基本操作
#include<iostream>
using namespace std;
typedef char elemtype;
typedef struct queuelist
{
elemtype data;
struct queuelist*next;
}node;//链队数据结点的类型
typedef struct
{
node*front;
node*rear;
}linkqueue;//链队结点的类型
void outall(linkqueue*&q)//全部元素出队列
{
node*t;
char e;
int i=0;
node*n=q->front;
while(n!=NULL)
{
if(q->rear==NULL)
cout<<"run error"<<endl;
t=q->front;
if(q->front==q->rear)
q->front=q->rear=NULL;
else
q->front=q->front->next;
e=t->data;
free(t);
i++;
n=q->front;
cout<<"元素"<<e<<"出队列,序号为:"<<i<<endl;
}
}
void outelem(linkqueue*&q,elemtype i)//第i个位置的元素出队
{
node*t;
char e;
int n=0;
while(i!=n)
{
if(q->rear==NULL)
cout<<"run error"<<endl;
t=q->front;
if(q->front==q->rear)
q->front=q->rear=NULL;
else
q->front=q->front->next;
e=t->data;
free(t);
n++;
}
cout<<"元素"<<e<<"出队列!"<<endl;
}
void enter(linkqueue*&q,elemtype e)//进队列
{
node*p;
p=(node*)malloc(sizeof(node));
p->data=e;
p->next=NULL;
if(q->rear==NULL)
q->front=q->rear=p;
else
{
q->rear->next=p;
q->rear=p;
cout<<e<<"进队成功!"<<endl;
}
}
void empty(linkqueue*q)//判断队列是否为空
{
if(q->rear==NULL)
cout<<"队空!"<<endl;
else
cout<<"非空!"<<endl;
}
void destroy(linkqueue*&q)//销毁队列
{
node*pre=q->front,*p;
if(pre!=NULL)
{
p=pre->next;
while(p!=NULL)
{
free(pre);
pre=p;
p=p->next;
}
}
free(pre);
cout<<"队列已销毁!"<<endl;
}
void init(linkqueue*&q)//初始化队列
{
q=(linkqueue*)malloc(sizeof(linkqueue));
q->front=q->rear=NULL;
}
int main()
{
linkqueue*q;
init(q);
empty(q);
enter(q,'a');
enter(q,'b');
enter(q,'c');
empty(q);
cout<<"输入想要出队元素的位置:";
int n;
cin>>n;
outelem(q,n);
enter(q,'d');
enter(q,'e');
enter(q,'f');
outall(q);
destroy(q);
return 0;
}
数据结构-链队列的基本操作
最新推荐文章于 2023-10-22 00:14:59 发布