c - 使用链表的优先级队列

标签 c linked-list priority-queue

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

该程序要求我将各种数据排序到单独的队列中......同一队列中的所有元素都具有相同的优先级。

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

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

Q1:A,C Q2:B

我的程序如下。我认为我弄乱了作为参数发送给函数 add 的指针...

`#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/

相关文章:

c - 需要帮助完成我的 ATM 机

c - 冒泡排序链表

c - 在链表中前进指针

java - 数据未保存在 ArrayList 中

c# - 任务并行库中的优先队列

c++ - 如何连接两个指向字符串的指针并将其存储在数组或字符中?

c - C 应用程序调试与 Release模式中的内存泄漏

c++ - 如何在Objective-C/C/C++中进行字符和字节位置的转换

algorithm - 优先队列 - 跳过列表与斐波那契堆

java - Java 中的 PriorityQueue 说明