#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
判滿等。通過模板類的方式實現,可以支持不同類型的元素入隊和出隊操作。