循环队列,定义循环队列长度为10,编写初始化队列、入队、出队、求队长,实现10,20,30,40,50,60,70,80入队,10,20,30出队,56,67入队的算法功能。

循环队列,定义循环队列长度为10,编写初始化队列、入队、出队、求队长,实现10,20,30,40,50,60,70,80入队,10,20,30出队,56,67入队的算法功能。

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define MAXQSIZE 100//最大队列长度
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -1
typedef int QElemType;
typedef int Status;
/*
循环队列
*/
typedef struct {
	int *base;//动态分配内存空间
	int front;//头指针,若队列非空,指向队列头元素
	int rear;//尾指针,若队列非空,指向队列元素的下一个位置

}SqQueue;
//初始化
void InitQueue(SqQueue &Q)
{ 
	 //构造一个空队列Q  
	printf("初始化队列开始\n");
	Q.base = (int *)malloc(MAXQSIZE * sizeof(int));
	if (!Q.base) // 存储分配失败   
		exit(-1);
	Q.front = Q.rear = 0;
	printf("初始化队列结束\n");
}
//入队
int EnQueue(SqQueue &Q, int e) {
	//printf("入队开始\n");
	if ((Q.rear + 1) % MAXQSIZE == Q.front) {
		return -1;
	}
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MAXQSIZE;
	//printf("入队结束\n");
	return 1;
}
//出队

int DeQueue(SqQueue &Q, int &e) {
	//printf("出队开始\n");
	if (Q.front == Q.rear) return -1;
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MAXQSIZE;
	//printf("%d\n", e);
	//printf("出队结束\n");
	return 1;
}
//求循环队列元素个数:
int QueueLength(SqQueue Q){
	return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
void main() {
	//SqQueue s;  int  main
	//InitQueue(s);
	//Enqueue(s, 5);
	//printf("队列长度为%d\n", QueueLength(s));
	//int e;
	//DeQueue(s, e);
	//printf("队列长度为%d\n", QueueLength(s));
	//return 0;

	SqQueue Q;
	InitQueue(Q);

	EnQueue(Q,10);
	EnQueue(Q,20);
	EnQueue(Q,30);
	EnQueue(Q,40);
	EnQueue(Q,50);
	EnQueue(Q,60);
	EnQueue(Q,70);
	EnQueue(Q,80);

	while(Q.front!=Q.rear){
		QElemType e=0;
		DeQueue(Q,e);
		printf("%d出队\n",e);
		if(Q.base[Q.front]<=30)
			continue;
		else{
			EnQueue(Q,56);
			EnQueue(Q,67);
			break;
		}
	}

	printf("队列Q:");
	while(Q.front!=Q.rear){
		QElemType e=0;
		DeQueue(Q,e);
		printf("%d  ",e);
	}
}

程序运行结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值