Queue using linked list

 2) Queue using Linked List

Aim

To implement queue operations (Enqueue, Dequeue, Display) using singly linked list in C.

Objective

  • To implement FIFO (First In, First Out) principle.

  • To study dynamic memory allocation in queues.

Algorithm

Enqueue:

  1. Create new node.

  2. If queue empty, set front = rear = new.

  3. Else insert at end (rear->next = new, rear = new).

Dequeue:

  1. If queue empty, print underflow.

  2. Else remove node at front.

  3. Update front pointer.

  4. If front becomes NULL, set rear = NULL.

Display:

  1. Traverse from front to rear.

  2. Print each node’s data.

Flowchart

Flowchart-Queue using Arrays

C Code (Queue using Linked List)

#include <stdio.h>

#include <stdlib.h>

struct Node {

    int data;

    struct Node* next;

};

int main() {

    struct Node *front = NULL, *rear = NULL, *temp;

    int choice, item;

    while (1) {

        printf("\n--- Queue Menu (Linked List) ---\n");

        printf("1. Enqueue\n2. Dequeue\n3. Display\n4. Exit\n");

        printf("Enter choice: ");

        scanf("%d", &choice);

        if (choice == 1) {  // Enqueue

            printf("Enter item to enqueue: ");

            scanf("%d", &item);

            struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

            newNode->data = item;

            newNode->next = NULL;

            if (rear == NULL) {

                front = rear = newNode;

            } else {

                rear->next = newNode;

                rear = newNode;

            }

        }

        else if (choice == 2) {  // Dequeue

            if (front == NULL)

                printf("Queue Underflow!\n");

            else {

                temp = front;

                printf("Dequeued: %d\n", temp->data);

                front = front->next;

                if (front == NULL) rear = NULL;

                free(temp);

            }

        }

        else if (choice == 3) {  // Display

            if (front == NULL)

                printf("Queue is Empty!\n");

            else {

                printf("Queue elements: ");

                temp = front;

                while (temp != NULL) {

                    printf("%d ", temp->data);

                    temp = temp->next;

                }

                printf("\n");

            }

        }

        else if (choice == 4) {

            printf("Exiting...\n");

            break;

        }

        else {

            printf("Invalid choice!\n");

        }

    }

    return 0;

}


Comments

Popular posts from this blog

Stack using array

Bubble Sort

Singly linked list implementation