Saturday, 9 August 2014

Insertion and deletion of elements in a queue

The following program is the insertion, deletion of elements in a queue. If you have any doubts please let me know.
#include<stdio.h>
#include<stdlib.h>
struct node
{
        int data;
        struct node *next;
}*newn,*f=NULL,*r=NULL,*temp=NULL;
void ins();
void del();
void display();
main()
{
   int ch;
   do
   {
       printf("\nMenu:\n1.Insert\n2.Delete\n3.Display\n4.Exit\n");
       printf("Enter your choice:");
       scanf("%d",&ch);
       switch(ch)
       {
          case 1:
                  ins();
                  break;
          case 2:
                  del();
                  break;
          case 3:
                  display();
                  break;
           case 4:
                   break;
           default:
                    printf("Wrong Choice!");
                    break;
       }
   }while(ch!=4);
}
void ins()
{
        int x;
        printf("Enter the value to be inserted:");
        scanf("%d",&x);
        newn=(struct node *)malloc(sizeof(struct node));
        newn->data=x;
        if((f==NULL)&&(r==NULL))
        {
                newn->next=NULL;
                f=newn;
                r=newn;
        }
        else
        {
                r->next=newn;
                newn->next=NULL;
                r=r->next;
        }
}
void del()
{
        if((f==NULL)&&(r==NULL))
                printf("\nQueue Underflow\n");
        else if(f==r)
       {
         temp=f;
         f=NULL;
         r=NULL;
         free(temp);
       }
        else
        {
                temp=f;
                f=f->next;
                free(temp);
        }
}
void display()
{
        if((f==NULL)&&(r==NULL))
                printf("\nQueue Underflow\n");
        else
        {
                temp=f;
                while(temp!=r)
                {
                        printf("=>%d  ",temp->data);
                        temp=temp->next;
                }
                printf("=>%d  ",r->data);
        }
}


No comments:

Post a Comment