我一直在尝试借助链表实现优先级队列。但是,当我使用下面的程序中使用的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;
}`
提前致谢! :)
最佳答案
函数“ add”中的循环如何?
while((*n)->next!=NULL) *n=(*n)->next;
你不是这个意思吗
while((*n)->next!=NULL) n=&(*n)->next;
关于c - 使用链表的优先队列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11557956/