温馨提示×

C++循环队列的应用实例

c++
小樊
87
2024-07-14 10:15:27
栏目: 编程语言

循环队列是一种具有固定大小的队列,当队列满时,新元素将会覆盖最旧的元素。下面是一个简单的C++循环队列的应用实例,实现了一个基本的生产者-消费者模型。

#include <iostream>
using namespace std;

#define SIZE 5

class CircularQueue {
private:
    int arr[SIZE];
    int front, rear;

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

    void enqueue(int value) {
        if ((front == 0 && rear == SIZE - 1) || (rear == (front - 1) % (SIZE - 1))) {
            cout << "Queue is full" << endl;
        } else if (front == -1) {
            front = rear = 0;
            arr[rear] = value;
        } else if (rear == SIZE - 1 && front != 0) {
            rear = 0;
            arr[rear] = value;
        } else {
            rear++;
            arr[rear] = value;
        }
    }

    int dequeue() {
        if (front == -1) {
            cout << "Queue is empty" << endl;
            return -1;
        }

        int value = arr[front];
        arr[front] = -1;
        if (front == rear) {
            front = rear = -1;
        } else if (front == SIZE - 1) {
            front = 0;
        } else {
            front++;
        }

        return value;
    }

    void displayQueue() {
        if (front == -1) {
            cout << "Queue is empty" << endl;
            return;
        }

        cout << "Elements in the circular queue are:" << endl;
        if (rear >= front) {
            for (int i = front; i <= rear; i++) {
                cout << arr[i] << " ";
            }
        } else {
            for (int i = front; i < SIZE; i++) {
                cout << arr[i] << " ";
            }

            for (int i = 0; i <= rear; i++) {
                cout << arr[i] << " ";
            }
        }
        cout << endl;
    }
};

int main() {
    CircularQueue q;

    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);
    q.enqueue(4);
    q.enqueue(5);

    q.displayQueue();

    cout << "Dequeued element: " << q.dequeue() << endl;

    q.enqueue(6);
    q.displayQueue();

    return 0;
}

在这个示例中,我们定义了一个CircularQueue类,实现了循环队列的基本功能,包括入队、出队和显示队列元素。在main函数中,我们演示了如何使用循环队列模拟生产者-消费者模型。首先入队5个元素,然后出队一个元素,最后再入队一个元素。最终打印出队列中的元素。

0