Sobes.tech
Junior — Middle

Can you explain how the data structure of a queue is implemented?

sobes.tech AI

Answer from AI

A queue is a data structure that operates on the FIFO (First In, First Out) principle, meaning the first entered element will be the first to be removed.

Implementations of a queue typically include:

  • Array or linked list for storing elements.
  • Two pointers or indices: front (head of the queue) and rear (tail of the queue).

Main operations:

  • enqueue — adding an element to the end of the queue;
  • dequeue — removing an element from the beginning of the queue;
  • peek/front — viewing the first element without removing it.

Example in C++ using an array and cyclic buffer:

class Queue {
    int* arr;
    int capacity;
    int front;
    int rear;
    int count;

public:
    Queue(int size) {
        arr = new int[size];
        capacity = size;
        front = 0;
        rear = -1;
        count = 0;
    }

    void enqueue(int item) {
        if (count == capacity) throw std::overflow_error("Queue is full");
        rear = (rear + 1) % capacity;
        arr[rear] = item;
        count++;
    }

    int dequeue() {
        if (count == 0) throw std::underflow_error("Queue is empty");
        int item = arr[front];
        front = (front + 1) % capacity;
        count--;
        return item;
    }

    int size() {
        return count;
    }

    bool isEmpty() {
        return count == 0;
    }

    ~Queue() {
        delete[] arr;
    }
};

This approach allows efficient memory usage and constant-time operations.