您的位置:首页 > 其它

链式队列基本操作

2015-08-04 09:45 239 查看
#include<stdio.h>
#include<stdlib.h>
typedef int dataType;
typedef struct  node
{
dataType data;
struct node *next;
}linklist;
typedef struct
{
linklist *front;
linklist *real;
}linkqueue;
void setnull(linkqueue *q)//置空
{
linklist *p=malloc(sizeof (linkqueue));
q->front=q->real=p;
q->front->next=NULL;
}
int  empty(linkqueue *q)//判断是否为空
{
return (q->front ==q->real);
}
void enqueue(linkqueue *q,dataType x)//入队
{
printf("入队:%d\n",x);
linklist *p=malloc(sizeof(linkqueue));
if(p==NULL)
{
printf("error\n");
exit(1);
}
p->data=x;
p->next=NULL;
if(empty(q))
{
q->front->next=p;
q->real=p;
}
else
{
q->real->next=p;
q->real=p;
}
return ;
}

dataType  dequeue(linkqueue *q)//出队
{
if(empty(q))
{
printf("queue is empty!\n");
return 0;
}
else
{
linklist *p;
p=q->front;
q->front=q->front->next;
free(p);
printf("\n出队:%d\n",q->front->data);
return (q->front->data);
}

}
void clearqueue(linkqueue *q)//清除所有元素
{
printf("\n清除队列中*************\n\n");
linklist *p;
p=q->front;
int count=1;
while(p!=NULL)
{

q->front=q->front->next;
free(p);
p=q->front;
}
q->real=NULL;
printf("清除完成\n");
}
void printqueue(linkqueue *q)//打印所有元素
{
linklist *s;
s=q->front->next;
while(s!=NULL)
{
printf("%d\t",s->data);
s=s->next;
}
printf("\n\n");

}
dataType real(linkqueue *q)//打印队尾元素
{
if(empty(q))
{
printf("queue is empty!\n");
}
else
return (q->real->data);

}
dataType front(linkqueue *q)//打印队首元素
{
if(empty(q))
{
printf("queue is empty!\n");
}
else
return (q->front->next->data);

}

void main()
{
linkqueue p;
setnull(&p);// 设为空
printf("\n是否为空?\n%d\n\n",empty(&p));//判断是否为空
enqueue(&p,2);//入队
enqueue(&p,3);//入队
enqueue(&p,4);//入队
printf("\n是否为空?\n%d\n\n",empty(&p));//判断是否为空
printf("\n打印队列:\n");
printqueue(&p);
printf("the front data:\n");
printf("%d\n",front(&p));//打印front
printf("the real data:\n");
printf("%d\n",real(&p));//打印real
dequeue(&p);//出队
printf("the front data:\n");
printf("%d\n",front(&p));//打印front
printf("\n打印队列:\n");
printqueue(&p);
clearqueue(&p);
printf("\n是否为空?\n%d\n",empty(&p));//判断是否为空
}

运行结果:
是否为空?
1

入队:2
入队:3
入队:4

是否为空?
0

打印队列:
2	3	4

the front data:
2
the real data:
4

出队:2
the front data:
3

打印队列:
3	4

清除队列中*************

清除完成

是否为空?
1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: