使用链表的优先队列

Posted

技术标签:

【中文标题】使用链表的优先队列【英文标题】:Priority Queue using linked lists 【发布时间】:2012-07-19 09:37:34 【问题描述】:

我一直在尝试借助链表来实现优先级队列。但是,当我使用我在下面的程序中使用的 add() 函数时,我无法将数据添加到列表中。一些帮助会很棒!

该程序要求我将各种数据分类到不同的队列中。同一队列中的所有元素具有相同的优先级。

即:数据:A,优先级:1 数据:B,优先级:2 数据:C,优先级:1

那么它应该按如下方式存储数据:

Q1 : A,C 第二季度: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;
       `

提前致谢! :)

【问题讨论】:

【参考方案1】:

函数“add”中的循环呢?

while((*n)->next!=NULL) *n=(*n)->next;

你不是这个意思吗?

while((*n)->next!=NULL) n=&(*n)->next;

【讨论】:

非常感谢!我刚刚意识到同样的事情。 :)【参考方案2】:

我看到的几个问题:

    在main中,q->next应该在“q=(struct node*)malloc(sizeof(struct node))”之后设置为null,否则可以是任何东西; 在del中,你实际上并没有删除任何东西(“malloc”分配的所有资源都应该被“free”释放); 同样在 del 中,“q->next”可能为空,因此“q->next->next”可能会导致程序崩溃

【讨论】:

以上是关于使用链表的优先队列的主要内容,如果未能解决你的问题,请参考以下文章

带链表的 C++ 优先级队列类

Dijkstra 算法运行时的区别:优先队列与双向链表

Leetcode23. 合并K个升序链表(优先队列)

如何使用优先队列对链表进行排序

Java 链表优先队列

优先级队列(从头开始)和链表