Please help me in C program and make sure it can run Create
Please help me in C++ program and make sure it can run
Create a node class/struct.
Create a queue class/struct.
Members:
Node - a node that tracks the front of the queue.
Node - a node that tracks the end of the queue.
Count - indicates how many items are on the queue.
Methods:
En-queue
- Accepts a number and adds to the end of the queue.
De-queue
- Returns a number from the front of the queue.
- If the queueis empty, emit an error indicating the queueis empty.
IsEmpty
- Returns a boolean indicating if the queue is empty.
Solution
A C++ program to demonstrate implementation of the queue
#include <stdlib.h>
#include <stdio.h>
// A linked list (LL) node to store a queue entry
struct Node
{
int key;
struct Node *next;
};
// The queue, front stores the front node of LL and rear stores ths
// last node of LL
struct Queue
{
struct Node *front, *rear;
int count;
};
// A utility function to create a new linked list node.
struct Node* newNode(int k)
{
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp->key = k;
temp->next = NULL;
return temp;
}
// A utility function to create an empty queue
struct Queue *createQueue()
{
struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
q->count = 0;
return q;
}
// The function to add a key k to q
void enQueue(struct Queue *q, int k)
{
// Create a new LL node
struct Node *temp = newNode(k);
// If queue is empty, then new node is front and rear both
if (q->rear == NULL)
{
q->front = q->rear = temp;
q->count = 1;
return;
}
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
q->count = q->count + 1;
}
//returns a boolean value to check whether the queue is empty or not.
bool isEmpty(struct Queue *q){
if(q->rear == NULL)
return true;
return false;
}
// Function to remove a key from given queue q
struct Node *deQueue(struct Queue *q)
{
// If queue is empty, return NULL.
if (q->front == NULL)
return NULL;
// Store previous front and move front one node ahead
struct Node *temp = q->front;
q->front = q->front->next;
q->count = q->count - 1;
// If front becomes NULL, then change rear also as NULL
if (q->front == NULL)
q->rear = NULL;
return temp;
}
Driver Program to test above functions
int main()
{
struct Queue *q = createQueue();
enQueue(q, 10);
enQueue(q, 20);
struct Node *n = deQueue(q);
if (n != NULL)
printf(\"Dequeued item is %d\ \", n->key);
printf(\"Count in the Queue %d\", q->count);
return 0;
}
Output :-
Dequeued item is 10
Count in the Queue 1

