Tuesday, 22 August 2023

Write a program to implement queue using linked list.

Queue Implementation in C using linked list.

Queue Implementation in C


#include stdio.h
#include stdlib.h

struct node
{
    int data;
    struct node *next;
} * head, *temp, *travel, *ptr;

void print()
{
    travel = head;
    if (travel == NULL)
    {
        printf("Linked-List is empty.\n");
    }
    else
    {
        while (travel != NULL)
        {
            printf("%d ", travel->data);
            travel = travel->next;
        }
    }
}

void add_at_last(int data)
{

    struct node *new_node = (struct node *)malloc(sizeof(struct node));
    struct node *last = head;
    new_node->data = data;
    new_node->next = NULL;
    if (head == NULL)
    {
        head = new_node;
        return;
    }

    while (last->next != NULL)
        last = last->next;

    last->next = new_node;
}

void del_first()
{
    if (head == NULL)
    {
        printf("\nLinked-List is Empty..");
    }
    else
    {
        printf("Deleted elemnt is %d", head->data);
        ptr = head;
        head = head->next;
        free(ptr);
        ptr = NULL;
    }
}

void main()
{
    int choice, n, t, key;

    while (1)
    {
        printf("\n1.INSERT ELEMENT INTO QUEUE\n2.DELETE ELEMENT FROM QUEUE\n3.DISPLAY QUEUE\n4.EXIT");
        scanf("%d", &choice);

        switch (choice)
        {
        case 1:
            printf("Enter the element::");
            scanf("%d", &t);
            add_at_last(t);
            break;
        case 2:
            del_first();
            break;
        case 3:
            print();
            break;
        case 4:
            exit(0);
        default:
            printf("\nEnter valid choice");
            break;
        }
    }
}

1 comment:

  1. Output::

    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT1

    Enter the element::12



    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT1

    Enter the element::23



    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT1

    Enter the element::36



    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT3

    12 23 36

    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT2

    Deleted element is 12

    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT3

    23 36

    1.INSERT ELEMENT INTO QUEUE

    2.DELETE ELEMENT FROM QUEUE

    3.DISPLAY QUEUE

    4.EXIT



    ReplyDelete

Interactive Report: Introduction to the Internet of Things (IoT) ...

Popular Posts