-1

このコードの問題点がわかりません。コンパイル中にエラーは発生しませんが、Enqueu の指定されたオプションの実行中に突然停止します。問題は Queue->rear->next=NULL の近くで発生していますが、これは私の見解では正しいです。どこが間違っているのかわかりません。

struct ListNode
{
       int data;
       struct ListNode *next;
};

struct Queue
{
      struct ListNode *front;
      struct ListNode *rear;
};

struct Queue *createQueue()
{
      struct Queue *Q;
      Q=malloc(sizeof(struct Queue));
      if(!Q)
           return NULL;
      Q->front=Q->rear=NULL;
      return Q;
}

int IsEmptyQueue(struct Queue *Q)
{
      return (Q->front==NULL);
}

int EnQueue(struct Queue *Q,int data)
{
    struct ListNode *newNode;
    newNode=malloc(sizeof(struct ListNode));
    if(!newNode)
               return NULL;
    newNode->data=data;
    newNode->next=NULL;
    Q->rear->next=newNode;
    Q->rear=newNode;
    if(Q->front==NULL)
                Q->front=newNode;
}

int main()
{
    int choice=0,size,n;
    struct Queue *q;
    while(1)
    {
         printf("\nEnter the following");
         printf("\n1. Create a queue "); 
         printf("\n2.Enqueue");
         printf("\n7.Exit ");
         scanf("%d",&choice);

         switch(choice)
         {
                    case 1:printf("\nCreate Queue");
                           q=createQueue();
                           break;
                    case 2:printf("\nInsert");
                           printf("\nEnter element to be inserted");
                           scanf("%d",&n);
                           EnQueue(q,n);
                           break;

                    case 7:exit(0);
                    break;

      }
   }
}
4

2 に答える 2

2

キューが空の場合、そのfrontメンバーrearNULLです。 EnQueue次にNULL、行内のポインターを逆参照します

Q->rear->next = newNode;

最初に呼び出されたとき。この行は不要なので、単純に削除できます。

あなたが見ることができる他のいくつかの小さなエラーがあります

  • createQueue漏れtempます。明らかにこれを宣言/割り当てる必要はありません
  • EnQueuemalloc の失敗に対するエラー処理がありませんnewNode。ここで "newNode Created" を出力すると、やや誤解を招く可能性があります。
  • %pキューの末尾へのポインターを出力するときに、フォーマット指定子として使用します。
于 2013-01-10T15:12:43.230 に答える
0

In createQueue()you set Q->frontand Q->rearto NULLbut in EnQueue()you are using Q->rear->next.

于 2013-01-10T15:12:55.347 に答える