数组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;
}