Menu
CoddyTech

练习 #3

Coddy 队列:数据结构系列 #2 课程的第 11 课,共 12 课。

让我们把队列升级为循环队列!

challenge icon

挑战

简单

升级你的 Queue 类,使其支持循环队列,并将类名改为 CircularQueue。

构造函数接受一个整数,表示循环队列的最大容量。队列已满时,如果有新元素入队,就会移除最早加入的元素(队首),为新元素腾出空间。请更新其他方法以支持这一功能。

亲手试试

#include <iostream>
#include <sstream>
#include <string>
#include "circular_queue.h"

int main() {
    std::string line;
    std::getline(std::cin, line);
    CircularQueue q(std::stoi(line));
    while (std::getline(std::cin, line)) {
        std::istringstream iss(line);
        std::string cmd;
        if (!(iss >> cmd)) continue;
        if (cmd == "enqueue") {
            int x; iss >> x; q.enqueue(x);
        }
        if (cmd == "dequeue") {
            q.dequeue();
        }
        if (cmd == "front") {
            std::cout << q.front() << std::endl;
        }
        if (cmd == "rear") {
            std::cout << q.rear() << std::endl;
        }
        if (cmd == "size") {
            std::cout << q.size() << std::endl;
        }
    }
    return 0;
}

队列:数据结构系列 #2中的所有课

自己练习: C 在线编译器