栈和队列3--循环队列(少用1位)

对于循环队列区分是队满还是队空,
有2种解决方法
1.少用1个元素

判空条件:front=rear=0,
判满条件:(Q.rear+1)% MaxSize==Q.front;
入栈:base[rear++]=e;		出栈:e=base[front++];

2.另设一个标志位,加以判断,如下一篇博客

==========================================
本篇结构:

从尾入,从头出

判空条件:front=rear=0,判满条件:(Q.rear+1)% MaxSize==Q.front

入栈:base[rear++]=e; 出栈:e=base[front++];

#include"pch.h"

#include<iostream>
#define MaxSize 200//循环队列最大长度
using namespace std;
typedef  int QElemType;//数据类型
typedef struct {
	QElemType *base;//
	int front;//头指针
	int rear;//尾指针
}SqQueue;
//1.初始化,队空条件:front=rear=0
bool InitQueue(SqQueue &Q) {
	//空队列
	Q.base = new QElemType[MaxSize];
	if (!Q.base)	return false;
	Q.front = Q.rear = 0; return true;
}
//解决假溢出问题,1,少用一个元素,判断满的条件:(Q.rear+1)% MaxSize==Q.front	2.设置标志位(暂未定)
//2.入列
bool EnQueue(SqQueue & Q,QElemType e) {
	if ((Q.rear + 1) % MaxSize == Q.front) return false;//循环队满
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MaxSize;//队尾加1
	return true;
}
//3.队长度
int QueueLength(SqQueue Q) {
	return (Q.rear + MaxSize - Q.front) % MaxSize;
}
//4.出队列,删除头元素
bool DeQueue(SqQueue &Q, QElemType &e) {
	if (Q.front == Q.rear)	return false;//判空
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MaxSize;
	return true;
}
//5.取头元素
QElemType GetTop(SqQueue Q) {
	if (Q.rear != Q.front)
		return Q.base[Q.front];
}
//6.遍历
void ShowQueue(SqQueue Q) {
	if (Q.front == Q.rear) cout << "队列空" << endl;
	while(Q.front!= Q.rear) {
		cout << Q.base[Q.front] << " ";
		Q.front = (Q.front + 1) % MaxSize;
	}
}
int main() {
	SqQueue  S; QElemType e;
	if (InitQueue(S))cout << "Succeed" << endl;
	else cout << "Failed" << endl;
	//入栈
	cout << "input e:\t";
	while (cin >> e) {//按"ctrl+z"结束输入
		EnQueue(S, e);
		cout << "input e:\t";
	}
	cout << "栈顶元素为" << GetTop(S) << endl;
	cout << "栈所有元素为" << endl;
	ShowQueue(S);
	cout << "栈长度为" << QueueLength(S) << endl;
	//出栈
	if(DeQueue(S, e))
	cout << "移除的头元素是" << e<<endl;
	else cout << "栈空" << endl;
	cout << "栈剩下所有元素为" << endl;
	ShowQueue(S);
	cout << "栈长度为" << QueueLength(S) << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

广大菜鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值