栈和队列4--循环队列(标志位)

解决假溢出问题,1,少用一个元素,
判断满的条件:(Q.rear+1)% MaxSize==Q.front
2.设置标志位(现在来定)
判断满:
if (Q.tag = = 1 && (Q.rear = = Q.front))
判断空:
if (Q.tag = = 0 && (Q.rear = = Q.front))

#include<iostream>
#define MaxSize 10//循环队列最大长度
using namespace std;
typedef  int QElemType;//数据类型
typedef struct {
	QElemType *base;
	int front;//头指针
	int rear;//尾指针
	int tag;//标志位
}SqQueue;
//1.初始化,队空条件:front=rear=0
bool InitQueue(SqQueue &Q) {
	//空队列
	Q.base = new QElemType[MaxSize];
	Q.base = (int*)malloc(MaxSize * sizeof(int));
	if (!Q.base)	return false;
	Q.front = Q.rear = 0;
	Q.tag = 0;
	return true;
}

//2.入列

bool EnQueue(SqQueue & Q, QElemType e) {
	if (Q.tag = =  1  &&  (Q.rear = = Q.front)) return false;//判断循环队满
	Q.base[Q.rear] = e;
	Q.rear = (Q.rear + 1)%MaxSize;//队尾加1
	if (Q.tag == 0)
		Q.tag = 1;//表示队列非空
	return true;
}

//3.队长度

int QueueLength(SqQueue Q) {
	return (Q.rear + MaxSize - Q.front) % MaxSize;
}

//4.出队列,删除头元素

bool DeQueue(SqQueue &Q, QElemType &e) {
	**if (Q.tag = = 0&&Q.front = = Q.rear)	return false;//判空**
	e = Q.base[Q.front];
	Q.front = (Q.front + 1) % MaxSize;
	if (Q.tag == 1)
		Q.tag = 0;//表示队列非满
	return true;
}

//5.取头元素


QElemType GetTop(SqQueue Q) {
	if (Q.tag == 0 && Q.front == Q.rear)
		return NULL;//判空
	else
		return Q.base[Q.front];
}
bool isEmpyt(SqQueue Q) {
	return Q.tag == 0 && Q.front == Q.rear;
}

//6.遍历


void ShowQueue(SqQueue Q) {
	QElemType e;
	while (!isEmpyt(Q)) {
		DeQueue(Q, e);
		cout << e << " ";
	}cout << endl;
}
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;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

广大菜鸟

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

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

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

打赏作者

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

抵扣说明:

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

余额充值