#include <stdio.h>
#include <stdlib.h>
typedef struct Qnode{
int data;
struct Qnode*next;
}Qnode,*QueuenPrt;
typedef struct{
QueuenPrt front;//头指针
QueuenPrt rear;//尾指针
}QList;
/*初始化队列*/
void InitQList(QList*L){
L->front=L->rear=(QueuenPrt)malloc(sizeof(Qnode));
if(!L->front){
printf("队列初始化失败\n");
}
else{
L->front->next=NULL;
}
}
/*摧毁队列*/
void Destroy(QList*L){
QueuenPrt p;
while(L->front){//头指针不在
p=L->front->next;
free(L->front);
L->front=p;
}
}
/*清空队列*/
void clearList(QList*L){
QueuenPrt p;
p=L->front->next;//判断头结点后是否有结点
while(p){
if(p==L->rear){//判断p是否等于尾指针,等于就让尾指针等于头指针在释放p
L->rear=L->front;
}
free(p);
}//清空队列后头指针还在
}
/*入队*/
void Indata(QList*L){
QueuenPrt p;
int i,x,j;
printf("请输入要入对的数据个数\n");
scanf("%d",&x);
printf("请输入要入队的数据\n");
for(i=0;i<x;i++){
p=(QueuenPrt)malloc(sizeof(Qnode));
scanf("%d",&j);
p->data=j;
p->next=NULL;
L->rear->next=p;
L->rear=p;//更新尾指针
}
}
/*判断队中的数据个数*/
void Lenght(QList*L){
int i=0;
QueuenPrt p;
p=L->front->next;
if(L->rear==L->front){
printf("该队列为空\n");
}
while(p){
i++;
p=p->next;
}
printf("队列长度为:%d\n",i);
}
/*出队*/
void Outdata(QList*L){
QueuenPrt p,q;
int i;
p=L->front->next;
if(L->rear==L->front){
printf("该队列为空\n");
}
else{
printf("请输入要出队的个数\n");
scanf("%d",&i);
}
while(p&& i){
printf("[%d]",p->data);
q=p->next;
if(p==L->rear){//出队的指针为尾指针时将他设为头指针
L->rear==L->front;
}
L->front->next=q;
free(p);
p=q;
i--;
}
printf("\n");
}
/*查看队列中的数据*/
void printfdata(QList*L){
QueuenPrt p;
p=L->front->next;
printf("队列中的数据为\n");
while(p!=NULL){
printf("[%d]",p->data);
p=p->next;
}
printf("\n");
}
int main(int argc, char *argv[]) {
QList L;
InitQList(&L);
Indata(&L);
printfdata(&L);
Lenght(&L);
Outdata(&L);
printfdata(&L);
Lenght(&L);
Destroy(&L);
return 0;
}
#效果展示