【问题标题】:Deleting all nodes inside a linked list删除链表中的所有节点
【发布时间】:2022-01-05 08:36:33
【问题描述】:

我已经创建了这个函数,我想删除链表中的所有节点。但是,它似乎不起作用,只删除了第一个节点 (?)。

void deleteList(Node* &pTemp) {
    Node *pCurrent = pTemp;
    Node* next = NULL;

    while(pCurrent != NULL) {
        next = pCurrent -> nextNode;
        free(pCurrent);
        pCurrent = next;
    }
}

我该怎么做才能删除每个节点,但仍然有一个空列表?

【问题讨论】:

  • 1.请提供一个最小的工作示例。 2. 看起来您不需要在 while 循环之外声明或初始化 next。 3.在C++中,我们使用nullptr作为空指针,使用newdelete操作符进行分配/释放。
  • 你永远不会修改pTemp,在取消引用时给调用者留下一个悬空指针和未定义的行为。
  • 在循环结束后添加pTemp = NULL;(或者,至少在将pTemp分配给pCurrent之后)。
  • 请提供足够的代码,以便其他人更好地理解或重现问题。

标签: c++ c++11


【解决方案1】:

请看here:

void deleteList(Node** head_ref)
{
 
    /* deref head_ref to get the real head */
    Node* current = *head_ref;
    Node* next = NULL;
 
    while (current != NULL)
    {
        next = current->next;
        free(current);
        current = next;
    }
 
    /* deref head_ref to affect the real head back
        in the caller. */
    *head_ref = NULL;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 2012-01-26
    • 1970-01-01
    • 2020-11-12
    • 2022-01-07
    相关资源
    最近更新 更多