b.
Perform the following operations using dynamic implementation of Queue
i. Insert n elements in a queue.
ii. Delete the element from the queue and display it.
#include <stdio.h>
#include <stdlib.h>
// Node structure to hold data and a pointer to the next node
struct Node {
int data;
struct Node* next;
};
// Queue structure holding pointers to the front and rear of the queue
struct Queue {
struct Node *front, *rear;
};
// Function to initialize an empty queue
void initialize(struct Queue* q) {
q->front = q->rear = NULL;
// Function to create a new node with the given value
struct Node* createNode(int value) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); // Allocate memory
newNode->data = value;
newNode->next = NULL;
return newNode;
}
// Enqueue operation: add element to the rear of the queue
void enqueue(struct Queue* q, int value) {
struct Node* newNode = createNode(value);
if (q->rear == NULL) {
// If the queue is empty, both front and rear are the new node
q->front = q->rear = newNode;
} else {
// Otherwise, link the new node at the end and update rear
q->rear->next = newNode;
q->rear = newNode;
printf("Enqueued: %d\n", value);
// Dequeue operation: remove and return element from the front of the queue
int dequeue(struct Queue* q) {
if (q->front == NULL) {
// If the queue is empty
printf("Queue is empty. Cannot dequeue.\n");
return -1;
struct Node* temp = q->front; // Store the front node
int value = temp->data; // Retrieve its data
q->front = q->front->next; // Move front to the next node
if (q->front == NULL) {
// If the queue becomes empty, also update rear
q->rear = NULL;
free(temp); // Free memory of the removed node
return value;
// Display all elements in the queue from front to rear
void display(struct Queue* q) {
if (q->front == NULL) {
printf("Queue is empty.\n");
return;
struct Node* temp = q->front;
printf("Queue elements: ");
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
printf("\n");
// Main function to execute the queue operations
int main() {
struct Queue q; // Declare a queue structure
initialize(&q); // Initialize the queue
int n, value;
// Ask the user how many elements to enqueue
printf("Enter number of elements to enqueue: ");
scanf("%d", &n);
// Input and enqueue n elements
printf("Enter %d integers:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &value);
enqueue(&q, value);
// Display the current queue
display(&q);
// Perform a dequeue operation
printf("Deleting (dequeuing) an element...\n");
int deleted = dequeue(&q);
// Display the dequeued element, if any
if (deleted != -1)
printf("Dequeued element: %d\n", deleted);
// Display the queue after deletion
display(&q);
return 0;