【数据结构与算法】用front、rear、MaxSize表示循环队列中元素个数 C++实现(循环队列+模运算)

数组a[MaxSize]用作一个循环队列,front指向循环队列中队头元素的前一个位置,rear指向队尾元素的位置。用front、rear、MaxSize表示队列中元素个数。


思路

对于循环队列,其头指针 front 和尾指针 rear 的位置可能在任意位置,所以不能直接通过 rear - front 来获取元素个数。需要通过 (rear - front + MaxSize) % MaxSize 这样的方式来获取元素个数。

首先,rear - front 计算出尾指针和头指针的距离,然后加上 MaxSize 以确保结果为正数(因为在循环队列中,rear 有可能小于 front)。最后,对 MaxSize 取余数,以确保结果在 [0, MaxSize) 的范围内。

时间复杂度为 O ( 1 ) O(1) O(1),空间复杂度也为 O ( 1 ) O(1) O(1)


代码

#include <algorithm>
#include <iostream>
#define AUTHOR "HEX9CF"
using namespace std;
using Status = int;
using ElemType = int;

const int N = 1e6 + 7;
const int MaxSize = 100;
const int TRUE = 1;
const int FALSE = 0;
const int OK = 1;
const int ERROR = 0;
const int INFEASIBLE = -1;
// const int OVERFLOW = -2;

int n;
ElemType a[N];

struct CircularQueue {
	ElemType a[MaxSize];
	int front, rear;
};

Status initQueue(CircularQueue &Q) {
	Q.front = Q.rear = 0;
	return OK;
}

bool queueFull(CircularQueue Q) { return ((Q.rear + 1) % MaxSize == Q.front); }

Status queuePush(CircularQueue &Q, ElemType e) {
	if (queueFull(Q)) {
		return ERROR;
	}
	Q.a[Q.rear] = e;
	Q.rear = (Q.rear + 1) % MaxSize;
	return OK;
}

int queueSize(CircularQueue &Q) {
	return ((Q.rear - Q.front + MaxSize) % MaxSize);
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> a[i];
	}

	CircularQueue Q;
	initQueue(Q);

	for (int i = 0; i < n; i++) {
		queuePush(Q, a[i]);
	}

	cout << queueSize(Q) << "\n";
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值