链表建立队列

#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;
}

#效果展示
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr pan cheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值