Search⌘ K
AI Features

Key Operations of a Queue

Understand key queue operations that manage data using the FIFO principle. Explore how to implement enqueue, dequeue, peek, isEmpty, and isFull functions in C++ for both array-based and linked list queues. This lesson covers essential queue manipulations, error handling, and their constant time complexities, building a foundation for efficient data processing.

Now that we understand how queues are implemented using arrays and linked lists, let us explore the fundamental operations for interacting with a queue. These operations define what makes a queue useful and how we manipulate the data it holds.

A queue supports several core operations, but they all revolve around the FIFO (First in, first out) principle. Before we can add or remove elements, we often need to check the queue’s current state. Let us begin with two essential utility operations.

The isEmpty operation

The isEmpty operation checks whether the queue contains any elements. This is crucial before attempting to remove or view elements, as attempting to dequeue from an empty queue results in an error.

Example: Consider a queue that currently holds the elements {88, 95, 72, 80, 91}. If we call isEmpty() on this queue, it would return false because the queue’s size is 5, not 0.

C++ implementation (array-based)

In an array-based queue, we can check if the queue is empty by comparing the size counter with 0. If size is equal to 0, no elements are present in the queue.

C++ 17
#include <iostream>
#include <vector>
class ArrayQueue {
private:
int capacity;
std::vector<int> data;
int front;
int rear;
int size;
public:
ArrayQueue(int cap = 10)
: capacity(cap), data(cap), front(0), rear(-1), size(0) {}
bool isEmpty() const {
return size == 0;
}
};
int main() {
ArrayQueue queue(10);
std::cout << "Is queue empty? " << (queue.isEmpty() ? "true" : "false") << std::endl;
// Output: true (queue is empty)
return 0;
}

If we were to dequeue all five elements one by one, size would eventually become 0 again. At that point, calling isEmpty() would return true.

The isFull operation

The isFull operation checks whether the queue has reached its maximum capacity. This is only relevant for array-based queues with a fixed size. Linked list-based queues can grow until the system runs out of memory, so isFull() is typically not needed for them.

Example: Consider a queue with capacity 5 that currently holds {88, 95, 72, 80, 91}. If we call the isFull() function, it would return true.

C++ implementation (array-based)

In an array-based queue, we check if ...