当前位置:首页 C++ > 正文

c++循环队列的实现

作者:野牛程序员:2023-08-24 12:12:16 C++阅读 2658

题目二:循环队列的实现

使用数组实现一个循环队列,需要考虑队满和队空的情况。


#include <iostream>

const int MAX_SIZE = 100;  // 假设队列的最大容量为100

class CircularQueue {
private:
    int queue[MAX_SIZE];
    int front;
    int rear;
public:
    CircularQueue() : front(0), rear(0) {}

    bool isEmpty() {
        return front == rear;
    }

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

    void enqueue(int value) {
        if (!isFull()) {
            queue[rear] = value;
            rear = (rear + 1) % MAX_SIZE;
        }
    }

    void dequeue() {
        if (!isEmpty()) {
            front = (front + 1) % MAX_SIZE;
        }
    }

    int frontValue() {
        if (!isEmpty()) {
            return queue[front];
        }
        return -1;  // 表示队列为空
    }
};

int main() {
    CircularQueue q;

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

    std::cout << q.frontValue() << std::endl;  // 输出:1

    q.dequeue();

    std::cout << q.frontValue() << std::endl;  // 输出:2

    return 0;
}

当然,以下是不使用类而使用数组来实现题目二(循环队列的实现)的代码示例:

#include <iostream>

const int MAX_SIZE = 100;  // 假设队列的最大容量为100

int queue[MAX_SIZE];
int front = 0;
int rear = 0;

bool isEmpty() {
    return front == rear;
}

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

void enqueue(int value) {
    if (!isFull()) {
        queue[rear] = value;
        rear = (rear + 1) % MAX_SIZE;
    }
}

void dequeue() {
    if (!isEmpty()) {
        front = (front + 1) % MAX_SIZE;
    }
}

int frontValue() {
    if (!isEmpty()) {
        return queue[front];
    }
    return -1;  // 表示队列为空
}

int main() {
    enqueue(1);
    enqueue(2);
    enqueue(3);

    std::cout << frontValue() << std::endl;  // 输出:1

    dequeue();

    std::cout << frontValue() << std::endl;  // 输出:2

    return 0;
}


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击