priority queue

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pradeep rajpoot
    New Member
    • Sep 2006
    • 5

    #1

    priority queue

    Hi everyone .I am trying to make a priority queue .I have written the code,complier is not giving any error but I am not getting the right answer.
    My program print only the last value that i have entered,and rest of the garbage value
    Code is:

    Code:
    struct node *getnode(struct node *,struct node *,int,int);
    void display(struct node *,int n) ;
    #include<stdio.h>
    #include<conio.h>
    #include<alloc.h>
    struct node
    {
    int data;
    int pri;
    struct node *link;
    };
    
    void main()
    {
    struct node *front,*rear;
    
    int a,n,pr,i;
    clrscr();
    front=NULL;
    rear=NULL;
    printf("\n\nEnter the no of the nodes you want to enter :");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
    printf("\n\nEnter the %d node element & its priority :",i+1);
    scanf("%d%d",&a,&pr);
    front=getnode(front,rear,a,pr);
    }
    display(front,n);
    getch();
    }
    
    struct node *getnode(struct node *front,struct node *rear,int a, int pr)
    {
    struct node *temp,*temp1;
    temp=(struct node*)malloc(sizeof(struct node));
    temp->data=a;
    temp->pri=pr;
    temp->link=NULL;
    if(rear==NULL)
    {
    rear=temp;
    front=rear;
    }
    else
    {
    
      if(front->pri<pr)
      {
    	temp->link=front;
    	front=temp;
     }
      else
     {
    	if(rear->pri>pr)
    	{
    	rear->link=temp;
    	rear=temp;
    	}
    	else
    	{
    	temp1=front;
    	while(temp->link->pri>=pr)
    	temp1=temp1->link;
    	temp->link=temp1->link;
    	temp1->link=temp;
    	}
      }
    }
    	return(front);
    }
    void display(struct node *front,int n)
    {
    struct node *temp  ;
    int i;
    temp=front;
    printf("\n\nElements and its priority :\n\n");
    for(i=0;i<n;i++)
    {
    printf("\n\n[%d,%d]",temp->data,temp->pri);
    temp=temp->link;
    }
    }
    Last edited by Banfa; Sep 28 '06, 01:38 PM. Reason: Added [code]...[/code] round the code
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    The problem lies in your definition of

    struct node *getnode(struct node *,struct node *,int,int);


    You pass front and rear as the first 2 parameters, these are of type struct node *.

    You are passing the pointers by value, this means that you can not alter their values in the main function. If you want to be able to alster the values they have in the main function then you need to pass the pointers by reference.

    i.e. struct node *getnode(struct node **,struct node **,int,int);

    Comment

    Working...