Friday 7 December 2012

Priority Queue program in C

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

void insert();
void show();
void del();

typedef struct node
{
    char info;
    int prior;
    struct node *next;
}n;
n *front=NULL,*rear=NULL;
int main()
{
    int ch;
    while(1)
    {
    printf("\n1. Insert Element");
    printf("\n2. Delete Element");
        printf("\n3. Show");
        printf("\n4. Exit");
        printf("\nChoice -: ");
    fflush(stdin);
    ch=getche();
    switch(ch)
    {
        case '1':
        insert();
        break;
        case '2':
        del();
        break;
        case '3':
        show();
        break;
        case '4':
        exit(0);
        break;
        default:
        printf("Wrong Input");
        getch();
        }
    }
}
void insert()
{
    n *ptr,*temp,*par;
    temp=(n*)malloc(sizeof(n));
    if(temp==NULL)
    {
        printf("Memory not allocated..");
        getch();
        exit(1);
    }
    printf("\nEnter data: ");
    fflush(stdin);
    scanf("%c",&temp->info);
    while(1)
    {
    printf("\nEnter Priority for '%c' data: ",temp->info);
    scanf("%d",&temp->prior);
    if(temp->prior > 0)
        break;
    }
    temp->next=NULL;

    if(front==NULL && rear==NULL)
    {
        front=rear=temp;
    }
    else
    {
        par=ptr=front;
        while((ptr->prior) <= (temp->prior) && ptr!=NULL)
        {
            par=ptr;
            ptr=ptr->next;
        }
        //node entering at rear
        if(ptr==NULL)
        {
            par->next=temp;
            temp->next=NULL;
            rear=temp;
        }
        //node entering before front
        else if(par==ptr)
        {
            front=temp;
            temp->next=ptr;
        }
        //node entering in middle
        else
        {
            par->next=temp;
            temp->next=ptr;
        }
    }
}
void show()
{
    n *ptr;
    printf("\nQueue: ");
    ptr=front;
    while(ptr!=NULL)
    {
        printf("%c\t",ptr->info);
        ptr=ptr->next;
    }
    getch();
}
void del()
{
    if(front==NULL)
    {
        printf("Priority Queue is Empty");
        getch();
        return;
    }
    printf("Element Deleted is '%c'",front->info);
    front=front->next;
}



-Gaurav Singhal
Like this page and comment about the program....
Thank You...

No comments: