2015-04-06 191 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