Monday, 9 December 2024

Write a program to implement a Dynamic Queue(Use pointer,linked list)

#include <stdio.h>

#include <stdlib.h>


struct node {

    int data;

    struct node *next;  // Pointer to the next node

};


// Function declarations

void create(struct node **front);

void enqueue(struct node **front, int val);

int dequeue(struct node **front);

void display(struct node **front);


int main() {

    struct node *front;  // Front pointer for the queue

    int choice, val;

    

    create(&front);  // Initialize the queue

    

    while(1) {

        printf("\n\n<<< MENU >>>");

        printf("\n1. Create\n2. Enqueue\n3. Dequeue\n4. Display\n5. Exit");

        printf("\nEnter your choice: ");

        scanf("%d", &choice);

        

        switch(choice) {

            case 1:

                create(&front);

                printf("\nQueue created successfully!");

                break;

            case 2:

                printf("\nEnter value to insert: ");

                scanf("%d", &val);

                enqueue(&front, val);

                printf("\nValue inserted successfully!");

                break;

            case 3:

                val = dequeue(&front);

                if(val == -999)

                    printf("\nQueue is empty!");

                else

                    printf("\n%d removed successfully!", val);

                break;

            case 4:

                display(&front);

                break;

            case 5:

                exit(0);

            default:

                printf("\nInvalid choice!");

        }

    }

    return 0;

}


// Initialize the queue (set front to NULL)

void create(struct node **front) {

    *front = NULL;

}


// Add an element to the queue (enqueue)

void enqueue(struct node **front, int val) {

    struct node *temp = (struct node *)malloc(sizeof(struct node));

    struct node *p;

    

    temp->data = val;

    temp->next = NULL;

    

    if (*front == NULL) {

        *front = temp;  // If queue is empty, make temp the first node

    } else {

        p = *front;

        while (p->next != NULL) {

            p = p->next;  // Traverse to the last node

        }

        p->next = temp;  // Add the new node to the end

    }

}


// Remove an element from the queue (dequeue)

int dequeue(struct node **front) {

    struct node *temp = *front;

    int x;

    

    if (temp == NULL) {

        return -999;  // Return -999 if the queue is empty

    } else {

        x = temp->data;  // Get the data of the front node

        *front = temp->next;  // Move the front pointer to the next node

        free(temp);  // Free the memory of the removed node

        return x;  // Return the data of the removed node

    }

}