我一直試圖通過鏈表來實現優先級隊列。但是,當我使用我在下面的程序中使用的add()函數時,我無法將數據添加到列表中。一些幫助會很棒!使用鏈表的優先級隊列
該程序要求我將各種數據分類到單獨的隊列中,同一隊列中的所有元素具有相同的優先級。
即:數據:A,優先級:1 數據:B,優先級:2 數據:C,優先級:1
那麼它應該存儲數據如下:
Q1:A, C Q2:B
我的程序如下。我想我搞亂了我發送的函數作爲參數添加的指針...
`#include<stdio.h>
#include<conio.h>
struct node{
char data[3];
struct node *next;
};
void del(struct node *);
void add(struct node *,struct node **);
void display(struct node *);
int main()
{
int i;
struct node *list[5];
struct node *q;
int pr,n;
for(i=0;i<5;i++)
list[i]=NULL;
printf("enter the no.of elements");
scanf("%d",&n);
for(i=0;i<n;i++)
{
q=(struct node*)malloc(sizeof(struct node));
printf("Enter data");
scanf("%s",&(q->data));
printf("\npriority :");
scanf("%d",&pr);
pr--;
add(q,&list[pr]);
}
for(i=0;i<5;i++)
{
display(list[i]);
}
for(i=0;i<5;i++)
del(list[i]);
getch();
return 0;
}
void add(struct node *q,struct node **n)
{
if(*n==NULL)
{
*n=q;
return;
}
while((*n)->next!=NULL)
*n=(*n)->next;
(*n)->next=q;
q->next=NULL;
return;
}
void del(struct node *q)
{
if(q==NULL)
{
printf("Queue empty");
return;
}
while(q->next->next!=NULL)
q=q->next;
q->next=NULL;
}
void display(struct node *q)
{
while(q!=NULL)
{
printf("%s\t",q->data);
q=q->next;
}
printf("\n");
return;
}`
在此先感謝! :)
由於一噸!我剛剛意識到這一點。 :) – Rahul 2012-07-19 11:21:39