【问题标题】:Remove value from front of queue in C从C中的队列前面删除值
【发布时间】:2014-02-06 11:19:09
【问题描述】:

我正在尝试使用此函数从队列的前面删除一个值。它似乎第一次工作(虽然我可能错了)但是当第二次释放节点时它触发了一个使程序崩溃的断点。我该如何解决这个问题?

printf("Value removed = %d\n", dequeue(myQueue));

int dequeue(queue q)
{
    if (q == NULL || q->head == NULL)
    {
        return 0;
    }

    node * head = q->head;
    node * temp = head;

    if (temp == NULL)
    {
        return;
    }

    int returnValue = head->value;

    //Free first node in queue
    head = temp->next;
    free(temp);

    //Return value that was removed
    return returnValue;
}

【问题讨论】:

  • 你忘记更新 q->head
  • 干杯。现在一切都好。 :)
  • 显示你的队列结构?
  • btw temp is head 所以if (temp == NULL){ return; } 不需要。
  • 请贴出queue的定义。

标签: c queue


【解决方案1】:

您更新了一个局部变量,而不是更新队列结构中的head q

head = temp->next;  // this is local variable 

应该是:

q->head = temp->next;

【讨论】:

  • 不幸的是,他似乎是按值传递结构,所以这没有解决任何问题。程序设计从根本上被破坏了。
  • @Lundin 不,他在函数中传递的是q 的结构地址,我建议更新q->head,这将反映任何方式的变化(代码不会改变q 本身)
  • 代码中没有任何内容表明他是通过指针传递的。我想他可能正在使用 typedef 来隐藏指针,但是程序设计仍然会从根本上被破坏......只是以另一种方式。
【解决方案2】:

传回更新后的队列,以便它在主函数中反映您的调用位置。或者您将仅更改函数调用结束后将弹出堆栈的本地结构

myQueue = dequeue(myQueue));


int dequeue(queue q)
{
if (q == NULL || q->head == NULL)
{
    return NULL;
}

node * temp = q->head; 

printf("Value removed = %d\n",head->value);

//Free first node in queue
q->head = temp->next;  
free(temp);

return q->head;

}

【讨论】:

    【解决方案3】:

    您是否将queue 定义为指针?那是非常糟糕的风格,永远不要这样做!它使代码完全不可读。

    否则,如果你还没有这样做,你也不应该通过值传递结构。如果你这样做了,你需要重新设计整个程序,以便它使用指针。所有功能都应遵循int dequeue(queue* q)的行。

    在上述任何一种情况下,您都需要退后一步,将整个链表 ADT 重新定义为有意义的东西。

    此外,仅此一项也无济于事,因为您只在 dequeue 函数中使用局部变量。正如其他人所展示的,您也必须更改实际的链表。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-18
      • 1970-01-01
      • 2016-06-22
      • 2012-12-17
      • 1970-01-01
      • 1970-01-01
      • 2012-10-27
      • 2014-09-17
      相关资源
      最近更新 更多