Follow This Blog For more... 😊

implement simple queue using Singly LinkedList |Using C language |Data Structure |

🤔Basically What is Queue and Singly Linked List?

⭕ Queue: A Queue is a linear data structure in which all the insertion(Enqueue) and deletion(Dequeue) of data or you can say its values are done at two different ends which are called rear and front respectively.

⇨ A queue has two pointers :
  1. Front pointer
  2. Rear pointer

⭕ Singly Linked List:  A Linked list is a linear data structure in which collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next.

⇨ In the Linked list Nodes are allocated Dynamically. [ Each node contains Data(information) part & Link(reference) part ]

⇨ Link part of each node points to its next node.

👨‍💻Write a program to implement a simple queue using Singly Linked List.

CODE:


    //in short make two functions 1.delete at front & 2.insert at rear

    #include<stdio.h>
    #include<stdlib.h>

    struct node
    {
        int data;
        struct node *link;
    };
    struct node *head=NULL;

    void delete_front();
    void insert_end();
    void display();
    int op_list();

    main()
    {
        int choice;
        choice = op_list();
        while(choice!=4)
        {
            switch(choice)
            {
                case 1:{insert_end();}break;
                case 2:{delete_front();}break;
                case 3:{display();}break;
                case 4:{exit(0);}break;
            }
            choice=op_list();
        }
    }

    void delete_front()
    {
        struct node *temp;
        if(head==NULL)
        {
            printf("queue is empty !!!");
        }
        else
        {
            temp=head;
            head=temp->link;
            free(temp);
        }
    }

    void insert_end()
    {
        struct node *p,*temp;
        p=(struct node *)malloc(sizeof(struct node));
        p->link=NULL;
        if(head==NULL)
        {
            head=p;
            printf("Enter the Data:");
            scanf("%d",&p->data);
        }
        else
        {
            for(temp=head;temp->link!=NULL;temp=temp->link)
            {

            }
            temp->link=p;
            printf("Enter the Data:");
            scanf("%d",&p->data);
        }
    }

    void display()
    {
        struct node *temp;
        printf("\n");
        if(head==NULL)
        {
            printf("queue is empty !!!");
        }
        else
        {
            for(temp=head;temp!=NULL;temp=temp->link)
            {
                printf("%d\n",temp->data);
            }
        }
            printf("\n");
    }

    int op_list()
    {
        int choice;
        printf("\nList of Operation\n1.Enqueue\n2.Dequeue\n3.Display\n4.Exit\nWhich operation you want to perform:");
        scanf("%d",&choice);
        return choice;
    }

OUTPUT:



Comments

Popular Posts