0

リンクされたリストを使用して優先キューを実装しようとしています。ただし、以下のプログラムで使用した 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;
       }`

前もって感謝します!:)

4

2 に答える 2

0

What about the cycle in function "add"?

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

Didn't you mean this?

while((*n)->next!=NULL) n=&(*n)->next;
于 2012-07-19T10:11:59.120 に答える
0

私が見たいくつかの問題:

  1. メインでは、q->next は "q=(struct node*)malloc(sizeof(struct node))" の後に null に設定する必要があります。それ以外の場合は何でもかまいません。
  2. del では、実際には何も削除していません (「malloc」によって割り当てられたすべてのリソースは、「free」によって解放される必要があります)。
  3. また、del では、「q->next」が null になる可能性があるため、「q->next->next」でプログラムがクラッシュする可能性があります
于 2012-07-19T10:57:56.537 に答える