If you have any query feel free to chat us!
Happy Coding! Happy Learning!
A queue can also be implemented using two pointers (front and rear) to keep track of the front and end of the queue. This is also known as a double-ended queue (deque).
Here's a C++ implementation of a Queue using two pointers:
cppCopy code
#include <iostream> const int MAX_SIZE = 100; class Queue { private: int arr[MAX_SIZE]; int frontIdx; int rearIdx; public: Queue() { frontIdx = -1; rearIdx = -1; } bool isEmpty() { return frontIdx == -1 && rearIdx == -1; } bool isFull() { return (rearIdx + 1) % MAX_SIZE == frontIdx || (frontIdx == 0 && rearIdx == MAX_SIZE - 1); } void enqueue(int element) { if (isFull()) { std::cout << "Queue is full. Cannot enqueue." << std::endl; return; } if (isEmpty()) { frontIdx = 0; rearIdx = 0; } else { rearIdx = (rearIdx + 1) % MAX_SIZE; } arr[rearIdx] = element; } void dequeue() { if (isEmpty()) { std::cout << "Queue is empty. Cannot dequeue." << std::endl; return; } if (frontIdx == rearIdx) { frontIdx = -1; rearIdx = -1; } else { frontIdx = (frontIdx + 1) % MAX_SIZE; } } int front() { if (isEmpty()) { std::cout << "Queue is empty." << std::endl; return -1; // Assuming -1 is not a valid element in the queue. } return arr[frontIdx]; } int size() { if (isEmpty()) { return 0; } return (rearIdx >= frontIdx) ? (rearIdx - frontIdx + 1) : (MAX_SIZE - frontIdx + rearIdx + 1); } }; int main() { Queue queue; queue.enqueue(10); queue.enqueue(20); queue.enqueue(30); std::cout << "Front element: " << queue.front() << std::endl; queue.dequeue(); std::cout << "Front element after dequeue: " << queue.front() << std::endl; std::cout << "Queue size: " << queue.size() << std::endl; return 0; }
In this implementation, we use an array to store the elements of the queue and two pointers
frontIdx
andrearIdx
to keep track of the front and rear of the queue. The queue is circular, and the modulo operator%
is used to handle the circular nature.The
enqueue()
function adds an element to the rear of the queue, thedequeue()
function removes the front element from the queue, and thefront()
function returns the front element without removing it. TheisEmpty()
andisFull()
functions check if the queue is empty or full, respectively. Thesize()
function returns the number of elements in the queue.In the
main
function, we demonstrate how to use the Queue by enqueueing and dequeueing elements and checking the front element and queue size.
Start the conversation!
Be the first to share your thoughts
Quick answers to common questions about our courses, quizzes, and learning platform