【问题标题】: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;
       }`

提前致谢! :)

【问题讨论】:

    标签: c linked-list priority-queue


    【解决方案1】:

    函数“add”中的循环呢?

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

    你不是这个意思吗?

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

    【讨论】:

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

    我看到的几个问题:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多