【问题标题】:Can't figure out how to clear a linked list in c++?无法弄清楚如何在 C++ 中清除链表?
【发布时间】:2013-11-05 19:42:29
【问题描述】:

我试图弄清楚如何清除堆栈(以链表的形式)。链表不是我的强项。我完全不理解他们。这是我的代码,任何人都可以解释为什么它不起作用?当我尝试通过 main 中的开关调用该方法时,它似乎也陷入了无限循环。

void stack :: clearStack()
{
if (isEmpty()== true)
{
    cout << "\nThere are no elements in the stack. \n";
}

else 
{
    node *current = top;
    node *temp;
    while(current != NULL);
    {
        current = temp -> next;
        delete current;
        current = temp;
    }
}

}

【问题讨论】:

  • 看起来你正在使用temp 而不需要初始化。
  • 我认为你应该多阅读并尝试更好地理解它们
  • for(node *p=top,*t; p ; p=t ) t=p-&gt;next, delete p;
  • while 末尾的分号也无济于事......下面的大多数答案只是复制了它,因此它们也不起作用。

标签: c++ list linked-list stack


【解决方案1】:

该代码存在一些问题。第一个是在循环之前取消引用一个未初始化的指针 (temp),另一个是 delete next 指针(因此可以说是把地毯拉到你自己的脚下)。

就这么简单

node* next;
for (node* current = top; current != nullptr; current = next)
{
    next = current->next;
    delete current;
}

哦,完成后别忘了清除top

【讨论】:

  • +1 我认为您可以利用 for 并声明 next 具有相同的范围。只是为了好玩;-)(正如我对这个问题的评论)。
  • 由于您正在清除列表,您实际上可以在列表中移动top,而不必在完成后清除它。
【解决方案2】:

你还没有初始化temp。您需要将temp 设置为列表的第一个节点。在循环内部,循环遍历节点并不断删除它们。

node *current = top;
node *temp = top; //    initialize temp to top
while(current != NULL);
{
    temp = temp -> next; // increase temp
    delete current;
    current = temp;
}

【讨论】:

    【解决方案3】:

    认为这就是你想要做的:

    node *current = top;
    while(current != NULL);
    {
        node *temp = current->next;
        delete current;
        current = temp;
    }
    top = null;
    

    【讨论】:

      【解决方案4】:
      if (isEmpty()== true)
      {
          cout << "\nThere are no elements in the stack. \n";
      }
      else 
      {
          node *current = top;
          node *temp;
          while(current != NULL);
          {
              current = temp -> next;
              delete current;
              current = temp;
          }
      }
      

      整个块可以替换为:

      while (top != nullptr)
      {
          unique_ptr<node> p(top);
          top = top->next;
      }
      

      如果列表已经为空,则什么也不做。如果它非空,unique_ptr 将控制当前top 的内存管理(这将在循环迭代之间删除它),将top 移动到next。当topNULL 时,所有内容都被清除,top 设置为NULL

      【讨论】:

        猜你喜欢
        • 2014-12-18
        • 1970-01-01
        • 2020-04-05
        • 2013-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多