链队列基本功能

本文详细介绍了链队列的数据结构,包括结点类型定义、队列类型定义,以及初始化、入队、出队、判断队列是否为空和遍历队列等函数的实现。
摘要由CSDN通过智能技术生成

目录

1.链队列类型定义

        1.1结点类型定义

        1.2队列类型定义

2.初始化队列

3.入队

4.出队

5.判断队列是否为空

6.遍历输出队列内所有元素

7.完整代码


1.链队列类型定义

        1.1结点类型定义

typedef struct LNode{ //结点数据类型 
	int elem;
	struct LNode *next;
}LNode;

        1.2队列类型定义

typedef struct{ //队列数据类型 
	LNode *front,*rear;
}LinkQueue;

2.初始化队列

void InitQueue(LinkQueue &Q){ //初始化 
	Q.front=Q.rear=(LNode*)malloc(sizeof(LNode));
	Q.front->next=NULL;
	Q.front->elem=NULL;
}

3.入队

void EnQueue(LinkQueue &Q,int x){ //入队 
	LNode *p=(LNode*)malloc(sizeof(LNode));
	p->elem=x;
	p->next=NULL;
	Q.rear->next=p;
	Q.rear=p;
}

4.出队

bool DelQueue(LinkQueue &Q,int &x){ //出队 
	if(Q.front==Q.rear)
		return false;
	LNode *q=Q.front->next; //头结点没有存储内容 
	x=q->elem;
	Q.front->next=q->next;
	q->next=NULL; //断链 
	if(q==Q.rear)
		Q.rear=Q.front;
	free(q);
	return true;
}

5.判断队列是否为空

bool IsEmpty(LinkQueue Q){ //判空 
	if(Q.front==Q.rear)
		return true;
	else
		return false;
}

6.遍历输出队列内所有元素

void PrintQueue(LinkQueue Q){ //输出 
	LNode *q=Q.front->next;
	while(q!=NULL){
		printf("%4d",q->elem);
		q=q->next;
	}
	printf("\n");
}

7.完整代码

#include <stdio.h>
#include <stdlib.h>

typedef struct LNode{ //结点数据类型 
	int elem;
	struct LNode *next;
}LNode;

typedef struct{ //队列数据类型 
	LNode *front,*rear;
}LinkQueue;

void InitQueue(LinkQueue &Q){ //初始化 
	Q.front=Q.rear=(LNode*)malloc(sizeof(LNode));
	Q.front->next=NULL;
	Q.front->elem=NULL;
}

void EnQueue(LinkQueue &Q,int x){ //入队 
	LNode *p=(LNode*)malloc(sizeof(LNode));
	p->elem=x;
	p->next=NULL;
	Q.rear->next=p;
	Q.rear=p;
}

bool DelQueue(LinkQueue &Q,int &x){ //出队 
	if(Q.front==Q.rear)
		return false;
	LNode *q=Q.front->next; //头结点没有存储内容 
	x=q->elem;
	Q.front->next=q->next;
	q->next=NULL; //断链 
	if(q==Q.rear)
		Q.rear=Q.front;
	free(q);
	return true;
}

bool IsEmpty(LinkQueue Q){ //判空 
	if(Q.front==Q.rear)
		return true;
	else
		return false;
}

void PrintQueue(LinkQueue Q){ //输出 
	LNode *q=Q.front->next;
	while(q!=NULL){
		printf("%4d",q->elem);
		q=q->next;
	}
	printf("\n");
}

int main(){
	LinkQueue Q;
	int x;
	InitQueue(Q);
	for(;;){
		scanf("%d",&x);
		if(x==-1)
	 		break;
		EnQueue(Q,x);
	}
	PrintQueue(Q);
	printf("判空:%d\n",IsEmpty(Q));
	DelQueue(Q,x);
	PrintQueue(Q);
	printf("出队元素:%d\n",x);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值