链式队列

在写二叉树的层次建立的时候,需要用到链式队列。自己写了很久,虽然对了,但还是懵懵懂懂。记录下一下。

#include<stdio.h>
#include<stdlib.h>
typedef struct Node{
	struct Node* next;
	int tdata;
}*position;//结点
typedef struct Qnode{
	position front,rear;
}*queue;//队列
queue creatqueue(){//建立队列
	queue a=(queue)malloc(sizeof(struct Qnode));
	a->front=a->rear=NULL;//这里两个指针,初始化时未开辟空间。当有元素入队时,指向新开辟的空间。
	return a;
}
bool isempty(queue q){
	return (q->front==NULL);
}
bool addq(queue q,int am){//入队列
	position p;
	p=(position)malloc(sizeof(struct Node));
	p->tdata=am;
	p->next=NULL;
	if(q->front==NULL)//为空队列的时候
	{
		q->front=q->rear=p;
	}
	else
	{
		q->rear->next=p;
		q->rear=p;	
	}
	return true;
}
int deletq(queue q){//出队
	if(isempty(q)) return 0;
	int am=q->front->tdata; 
	position tep=q->front;
	if(q->front==q->rear) q->front=q->rear=NULL;//队列里面只有一个元素的时候
	else q->front=q->front->next;
	free(tep);
	return  am;
}
void freequeue(queue q)//释放内存
{
	position tep;
	if(!q->front){//队列为空,不需要释放内存即可
		return;
	}//没有的话,程序异常退出。。
	while(q->front->next!=NULL)
	{
		tep=q->front;
		q->front=q->front->next;
		free(tep); 
	}
	free(q->front);
}
void disqueue(queue q)//打印队列里面元素
{
	position p=q->front;
	if(!p) printf("空");
	else
	{
		while(p)
		{
			printf("%d   ",p->tdata);
			p=p->next;
		} 
	}
	
} 
int main(){
	queue q=creatqueue();
	int num;
	while(scanf("%d",&num),num!=-1)
	{
		addq(q,num);		
	}
	deletq(q);
	deletq(q);
	disqueue(q);
	freequeue(q);
	return 0;
	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值