#include <iostream>
template <class T>
class CircularQueue {
private:
int front, rear, maxSize;
T* queueArray;
public:
CircularQueue(int size) {
maxSize = size + 1; // one extra space for checking full condition
front = rear = 0;
queueArray = new T[maxSize];
}
~CircularQueue() {
delete[] queueArray;
}
bool isEmpty() {
return front == rear;
}
bool isFull() {
return (rear + 1) % maxSize == front;
}
void enqueue(T item) {
if (isFull()) {
std::cout << "Queue is full, cannot enqueue.\n";
} else {
rear = (rear + 1) % maxSize;
queueArray[rear] = item;
}
}
T dequeue() {
if (isEmpty()) {
std::cout << "Queue is empty, cannot dequeue.\n";
return T();
} else {
front = (front + 1) % maxSize;
return queueArray[front];
}
}
};
int main() {
CircularQueue<int> queue(5);
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
queue.enqueue(4);
queue.enqueue(5);
queue.enqueue(6);
std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
std::cout << "Dequeued item: " << queue.dequeue() << std::endl;
return 0;
}
这段代码实现了一个循环队列的模板类CircularQueue
,其中包括了队列的基本操作:enqueue
入队、dequeue
出队、isEmpty
判空、isFull
判满等。通过模板类的方式实现,可以支持不同类型的元素入队和出队操作。