Menu
Coddy logo textTech

Practice #3

Lesson 11 of 12 in Coddy's Queue - Data Structures Series #2 course.

Let's upgrade the Queue to a circular queue!

challenge icon

Challenge

Easy

Upgrade your Queue class to support a circular queue, and rename the class to CircularQueue.

The constructor takes an integer — the maximum size of the circular queue. When the queue is full and a new item is enqueued, the oldest item (the front) is removed to make room. Update the other methods to support this.

Try it yourself

#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;
}

All lessons in Queue - Data Structures Series #2