队列基本操作

此队列操作烂熟于心:

#include <stdio.h>
#include <stdlib.h>
#define ElemType int
#define Status int
#define OK 1
#define ERROR 0
#define OVERFLOW -1

typedef struct Node{	//队列的一个节点
	ElemType data;
	struct Node *next;
}Node,*QueuePtr;

typedef struct{
	QueuePtr front;//头部指针
	QueuePtr rear;//尾部指针
}LinkQueue;//链表实现的队列

//初始化队列
Status InitQueue(LinkQueue &Q){
	//初始化的节点并未给data赋值,相当于头结点,我们可以用他来存队列长度
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(Node));
	if(!Q.rear){
		exit(OVERFLOW);
	}
	Q.front->data = 0;//长度初始化为0
	Q.front->next = NULL;
	return OK;
}
//入队
Status EnQueue(LinkQueue &Q,ElemType e){
	QueuePtr p = (QueuePtr)malloc(sizeof(Node));
	if(!p){
		exit(OVERFLOW);
	}
	p->data = e;
	p->next  = NULL;
	Q.rear->next = p;//连接p节点
	Q.rear = p;//移动rear指针始终指向尾部
	Q.front->data++;
	return OK;
}
//出队
Status DeQueue(LinkQueue &Q,ElemType &e){
	if(Q.rear == Q.front){//队列为空
		return ERROR;
	}
	QueuePtr p = Q.front->next;//跳过头结点
	e = p->data;
	Q.front->next = p->next;
	if(p == Q.rear){//如果除了头结点外只有一个节点
		Q.rear = Q.front;//如果不执行这步,free(p)后Q.rear也将不复存在
	}
	free(p);
	Q.front->data--;
	return OK;
}
//打印队列元素
void PrintQueue(LinkQueue Q){
	ElemType e;
	while(Q.rear != Q.front){
		DeQueue(Q,e);
		printf("%d ",e);
	}
	printf("\n");
}
//
int GetQueueLength(LinkQueue Q){
	return Q.front->data;
}
//销毁队列
void Destroy(LinkQueue &Q){
	//从队头开始销毁到队尾
	while(Q.front){
		Q.rear = Q.front->next;
		free(Q.front);
		Q.front = Q.rear;
	}
}
int main(){
	int i = 5;
	LinkQueue Q1,Q2;
	InitQueue(Q1);
	InitQueue(Q2);
	printf("...队列初始化完成\n");
	printf("输入5个元素:");
	ElemType e;
	while(i-->0){
		scanf("%d",&e);
		EnQueue(Q1,e);
		EnQueue(Q2,e);
	}
	printf("队列元素为:");
	PrintQueue(Q1);
	DeQueue(Q2,e);
	printf("DeQueue出的元素:%d\n",e);
	printf("队列长度为:%d\n",GetQueueLength(Q2));
	printf("队列元素为:");
	PrintQueue(Q2);
	Destroy(Q2);
	Destroy(Q1);
	printf("销毁队列完成\n");
	return 0;
}


运行结果:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值