Data Structures 2024-10-02 C++ 2 min read
Initializes a new empty queue with allocated memory.
template <typename T>
struct Node
{
T data;
Node<T> *next;
Node<T>(T data) : data(data), next(nullptr) {}
};
template <typename T>
Queue<T>::Queue()
{
this->front = nullptr;
this->rear = nullptr;
}
Frees up the memory used by the queue when it is destroyed.
template <typename T>
Queue<T>::~Queue()
{
while (this->front != nullptr)
{
this->dequeue();
}
}
Adds an item to the end of the queue.
template <typename T>
void Queue<T>::enqueue(T value)
{
Node<T> *newNode = new Node<T>(value);
if (this->isEmpty())
{
this->front = this->rear = newNode;
}
else
{
this->rear->next = newNode;
this->rear = newNode;
}
}
Removes the item at the front of the queue.
template <typename T>
void Queue<T>::dequeue()
{
if (!this->isEmpty())
{
Node<T> *temp = this->front;
this->front = this->front->next;
if (this->front == nullptr)
{
this->rear = nullptr;
}
delete temp;
}
}
Returns the item at the front of the queue without removing it.
template <typename T>
T Queue<T>::peek()
{
return (!this->isEmpty()) ? this->front->data : -1;
}
Checks if the queue is empty.
template <typename T>
bool Queue<T>::isEmpty()
{
return this->front == nullptr;
}
#include <iostream>
#include "Queue.h"
int main() {
Queue<int> *q = new Queue<int>(); // Create a queue for integers
std::cout << "Enqueuing elements{1,2,3,4}..." << std::endl;
q->enqueue(1);
q->enqueue(2);
q->enqueue(3);
std::cout << "Current front element: " << q->peek() << std::endl; // Should print 1
std::cout << "Dequeuing..." << std::endl;
q->dequeue();
std::cout << "New front element after one dequeue: " << q->peek() << std::endl; // Should print 2
std::cout << "Checking if queue is empty: " << (q->isEmpty() ? "Yes" : "No") << std::endl; // Should print No
std::cout << "Dequeuing remaining elements..." << std::endl;
q->dequeue();
q->dequeue(); // Queue should be empty after this
std::cout << "Checking if queue is empty after dequeuing all elements: " << (q->isEmpty() ? "Yes" : "No") << std::endl; // Should print Yes
try {
std::cout << "Attempting to peek into an empty queue: ";
std::cout << q->peek() << std::endl;
} catch (const std::runtime_error& e) {
std::cout << e.what() << std::endl; // Should catch and print "Queue is empty"
}
return 0;
}
Comments
Be the first one to comment!