中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

C++循環隊列的實現方法

c++
小樊
82
2024-07-14 10:11:27
欄目: 編程語言

#include <iostream>

#define MAX_SIZE 10

class CircularQueue {
private:
    int front, 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 value) {
        if (isFull()) {
            std::cout << "Queue is full. Cannot enqueue.\n";
            return;
        }

        if (isEmpty()) {
            front = 0;
            rear = 0;
        } else {
            rear = (rear + 1) % MAX_SIZE;
        }

        queue[rear] = value;
        std::cout << value << " enqueued to the queue.\n";
    }

    void dequeue() {
        if (isEmpty()) {
            std::cout << "Queue is empty. Cannot dequeue.\n";
            return;
        }

        std::cout << queue[front] << " dequeued from the queue.\n";

        if (front == rear) {
            front = -1;
            rear = -1;
        } else {
            front = (front + 1) % MAX_SIZE;
        }
    }

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

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

int main() {
    CircularQueue q;

    q.enqueue(10);
    q.enqueue(20);
    q.enqueue(30);
    q.display();

    q.dequeue();
    q.display();

    q.enqueue(40);
    q.display();

    return 0;
}

0
湾仔区| 乌鲁木齐县| 阳原县| 新化县| 黄山市| 藁城市| 济源市| 万州区| 咸宁市| 大安市| 乌拉特后旗| 霸州市| 蒙城县| 电白县| 象山县| 莒南县| 澄江县| 汉寿县| 南安市| 平远县| 淮阳县| 湘西| 乐安县| 阜城县| 瑞安市| 涟水县| 汤阴县| 甘孜县| 大兴区| 游戏| 宁强县| 岑巩县| 湖北省| 平阴县| 偏关县| 政和县| 奇台县| 万盛区| 深州市| 邵阳县| 承德县|