2015-04-06 339 views
0

我插入元件在隊列中,但無限循環運行 // x被被輸入無限循環

void enqueue(int x) 
    { 
    queue *ptr; 
    ptr=(queue*)malloc(sizeof(queue)); 
    ptr->info=x; 
    if(front==NULL&&rear==NULL) 
    { 
     front=rear=ptr; 
     ptr->next=NULL; 
    } 
    else 
    { 
    rear->next=ptr; 
    rear=ptr; 
    } 
} 

//顯示功能打印元件的元件

void show() 
    { 
    queue *ptr=front; 
    while(ptr!=NULL) 
    { 
     printf("%d\n",ptr->info); 
     ptr=ptr->next; 
    } 
    } 
+0

標準警告:請[不要轉換](http://stackoverflow.com/q/605845/2173917)''malloc()'和家族在'C'的返回值。 – 2015-04-06 11:45:47

+0

演員之間有衝突,不要在上述討論中施展衝突,所以要遵循哪一個 – Dumb 2015-04-06 11:57:25

回答

0

你只是在你的情況下一個設置ptr->nextNULL設置,你應該做兩個(或if聲明完全外):

void enqueue(int x) { 
    queue *ptr = malloc (sizeof (*ptr)); 

    // should really check for NULL here first 

    ptr->info = x; 
    ptr->next = NULL; 

    // If front is NULL, rear should be as well, 
    // so only need check one. 

    if (front == NULL) { 
     front = rear = ptr; 
    } else { 
     rear->next = ptr; 
     rear = ptr; 
    } 
} 

你會發現一對夫婦,我已經修復其他的東西,具體是:

  • 拆除的鑄造返回值爲malloc,這可能是危險的。
  • 儘量縮短代碼。
  • 刪除冗餘檢查,如頭部尾部指針。
  • 建議你檢查所有可能失敗的操作,特別是如果它們可能引起災難性的影響,如malloc可能。
1

你需要添加ptr->next=NULL這在你的情況下設置在if循環中。它應該在這兩個條件

void enqueue(int x) 
    { 
    queue *ptr; 
    ptr=malloc(sizeof(queue)); // As sourav mentioned you don't need to cast here 
    ptr->info=x; 
    ptr->next=NULL; 
    if(front==NULL&&rear==NULL) 
    { 
     front=rear=ptr; 
     //ptr->next=NULL; 
    } 
    else 
    { 
    rear->next=ptr; 
    rear=ptr; 
    } 
} 
+2

標準警告重複:請[不要轉](http://stackoverflow.com/q/605845/2173917)返回值'malloc()'和'C'中的家族。 – 2015-04-06 11:44:42

+0

@SouravGhosh直到今天我都不知道......謝謝... – Srinath 2015-04-06 11:46:12

+0

不客氣。 :-) – 2015-04-06 11:46:45