C++实现一个循环队列

#include 

#define MAX_SIZE 5

// CircularQueue类包含了循环队列的常见操作,
// 如isEmpty(判断队列是否为空)、isFull(判断队列是否已满)、
// enqueue(入队)、dequeue(出队)和display(显示队列中的元素)。
class CircularQueue {
private:
    int front;
    int rear;
    int queue[MAX_SIZE];

public:
    CircularQueue() {
        front = -1;
        rear = -1;
    }

    bool isEmpty() {
        return (front == -1 && rear == -1);
    }

    bool isFull() {
        return ((rear + 1) % MAX_SIZE == front);
    }

    void enqueue(int data) {
        if (isFull()) {
            std::cout << "Queue is full. Cannot enqueue." << std::endl;
            return;
        }
        else if (isEmpty()) {
            front = 0;
            rear = 0;
        }
        else {
            rear = (rear + 1) % MAX_SIZE;
        }

        queue[rear] = data;
        std::cout << "Enqueued " << data << std::endl;
    }

    void dequeue() {
        if (isEmpty()) {
            std::cout << "Queue is empty. Cannot dequeue." << std::endl;
            return;
        }
        else if (front == rear) {
            front = -1;
            rear = -1;
        }
        else {
            front = (front + 1) % MAX_SIZE;
        }
    }

    void display() {
        if (isEmpty()) {
            std::cout << "Queue is empty." << std::endl;
            return;
        }

        std::cout << "Queue: ";
        int i = front;
        while (i != rear) {
            std::cout << queue[i] << " ";
            i = (i + 1) % MAX_SIZE;
        }
        std::cout << queue[rear] << std::endl;
    }
};

int main() {
    CircularQueue queue;

    queue.enqueue(1);
    queue.enqueue(2);
    queue.enqueue(3);
    queue.enqueue(4);
    queue.enqueue(5);
    queue.enqueue(6); // Queue is full. Cannot enqueue.

    queue.display(); // Queue: 1 2 3 4 5

    queue.dequeue();
    queue.dequeue();

    queue.display(); // Queue: 3 4 5

    return 0;
}

你可能感兴趣的:(C++,c++,循环队列)