栈和队列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"pch.h"

#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;
}
发布了122 篇原创文章 · 获赞 14 · 访问量 6186

猜你喜欢

转载自blog.csdn.net/weixin_44001521/article/details/103745941
今日推荐