C:Program:Queue using linked list


This C Program implements queue using linked list. Queue is a particular kind of abstract data type or collection in which the entities in the collection are kept in order and the principal (or only) operations on the collection are the addition of entities to the rear terminal position, known as enqueue, and removal of entities from the front terminal position, known as dequeue. This makes the queue a First-In-First-Out (FIFO) data structure. Linked list is a data structure consisting of a group of nodes which together represent a sequence. Here we need to apply the application of linked list to perform basic operations of queue.

PROGRAM:

#include <stdio.h>
#include<stdlib.h>
void insert(int n);
void delete();
void display();
typedef struct node
{
    int data;
    struct node *link;
}snode;
snode *head,*tail;
void insert(int n)
{
    snode *newnode;
    newnode=(snode*)malloc(sizeof(snode));
    newnode->data=n;
    newnode->link=NULL;
    if(head==NULL)
    {
        head=newnode;
        tail=newnode;
     
    }
    else
    {
        tail->link=newnode;
        tail=newnode;
    }
}
void delete()
{
    snode *temp;
    if(head==NULL)
    {
    printf("\n No linked list created so far");
    }
    else
    {
     if(head==tail)
     {
        free(head);
        free(tail);
        head=tail=NULL;
     
     }
     else
     {
     temp=head;
     head=head->link;
   
     free(temp);
     }
    }
}
void display()
{
    snode *temp;
    if(head==NULL)
    printf("\nNo linked list");
    else
    {
        for(temp=head;temp!=NULL;temp=temp->link)
        {
            printf("%d\t",temp->data);
        }
    }
}
void main()
{
    int op,n;
    while(1)
    {
        printf("\n1:Insert\n2:Delete\n3:Display\n4:Exit");
        printf("\n Enter an option");
        scanf("%d",&op);
        switch(op)
        {
     
            case 1:printf("\n Enter an element");
            scanf("%d",&n);
            insert(n);
            break;
            case 2:
            delete();
            break;
            case 3:display();
            break;
            case 4:exit(0);
        }
    }
}

Recommended: solve it on “PRACTICE ” first, before moving on to the solution.

Previous Post Next Post