Monday, 23 January 2017

C program to implement Ascending Priority Queue



Algorithm to insert a value in ascending priority queue:
Let head be a pointer that stores the address of first node
step 1: Read the value and its priority
step 2: create a new node using malloc function
step 3: Assign the value read to the data field of newnode (newnode -> data =value)
                                        and newnode -> pri = priority
step 4: store the address of node whose priority is > newnode priority in pointer c
step 5: store the address of node before c in pointer p
step 5: newnode –> next = p->next
step 6: p -> next = newnode



 Program


#include<stdio.h>
#include <stdlib.h>
struct node
{
            int data,pri;
            struct node *next;
};
struct node *head=NULL,*c,*p;
void create();
void display();
main()
{
            int n,i;
            printf("enter the number of elements");
            scanf("%d",&n);
            for(i=1;i<=n;i++)
                        create();
                        display();
}
void create()
{
            int v,priority;
            printf("enter value and priority\n");
            scanf("%d%d",&v,&priority);
            struct node *newnode = (struct node *)malloc(sizeof(struct node));
            newnode->data =v;
            newnode->pri=priority;
            newnode->next = NULL;
            if(head == NULL)
                        head = newnode;
            else if( newnode->pri < head->pri)
            {          
                        newnode->next=head;
                        head=newnode;
            }
            else
            {
                        c=head;
                        while(newnode->pri >=c->pri && c->next != NULL)
                        {
                                    p=c;
                                    c=c->next;
                        }
                        if(c->next == NULL && newnode->pri >= c->pri)
                        {
                                    c->next = newnode;
                        }
                        else
                        {
                                    p->next=newnode;
                                    newnode->next=c;
                        }
            }
}
void display()
{
            if(head == NULL)
                        printf("list is empty");
            else
            {
                        c=head;
                        while(c != NULL)
                        {
                                    printf("%d  %d->",c->data,c->pri);
                                    c=c->next;
                        }
            }
}





No comments:

Post a Comment