Question: #include class Node { public: int value; Node * next; Node ( int value = 0 ) { this - > value = value; this

#include
class Node {
public:
int value;
Node* next;
Node(int value =0){
this->value = value;
this->next = nullptr;
}
};
class Queue {
private:
Node* front_node;
Node* rear_node;
public:
Queue(){
this->front_node = nullptr;
this->rear_node = nullptr;
}
bool isEmpty(){
return this->front_node == nullptr;
}
void enqueue(int value){
Node* new_node = new Node(value);
if (this->rear_node == nullptr){
// If the queue is empty, both front and rear nodes will point to the new node
this->front_node = this->rear_node = new_node;
} else {
// Attach the new node to the end of the queue and update the rear node
this->rear_node->next = new_node;
this->rear_node = new_node;
}
}
int dequeue(){
if (this->isEmpty()){
throw std::out_of_range("dequeue from empty queue");
}
int value = this->front_node->value;
this->front_node = this->front_node->next;
if (this->front_node == nullptr){
// If the queue becomes empty after dequeue, reset the rear_node as well
this->rear_node = nullptr;
}
return value;
}
int front(){
if (this->isEmpty()){
throw std::out_of_range("front from empty queue");
}
return this->front_node->value;
}
};
int main(){
Queue queue;
std::cout << std::boolalpha << queue.isEmpty()<< std::endl; // Output: true
queue.enqueue(1);
queue.enqueue(2);
queue.enqueue(3);
std::cout << std::boolalpha << queue.isEmpty()<< std::endl; // Output: false
std::cout << queue.front()<< std::endl; // Output: 1
std::cout << queue.dequeue()<< std::endl; // Output: 1
std::cout << queue.front()<< std::endl; // Output: 2
std::cout << queue.dequeue()<< std::endl; // Output: 2
std::cout << queue.front()<< std::endl; // Output: 3
std::cout << queue.dequeue()<< std::endl; // Output: 3
std::cout << std::boolalpha << queue.isEmpty()<< std::endl; // Output: true
return 0;
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!