无法弄清楚如何清除c ++中的链表? [英] Can't figure out how to clear a linked list in c++?

查看:103
本文介绍了无法弄清楚如何清除c ++中的链表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图弄清楚如何清除堆栈(以链表的形式).链接列表不是我的强项.我一点都不明白.这是我的代码,有人可以阐明为什么它不起作用吗?当我尝试通过main中的一个开关调用该方法时,似乎也陷入了无限循环.

I'm trying to figure out how to clear a stack (in the form of a linked list). Linked lists aren't my forte; I don't understand them at all. Here's my code, can anyone shed some light onto why it's not working? When I try to call the method through a switch in main, it seems too get stuck in an infinite loop.

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),而在循环之前先取消引用delete next指针(这样可以说是在您自己的脚下拉了地毯).

There are a few problems with that code. The first is that you dereference an uninitialized pointer (temp) the other that you delete the next pointer before you loop (and thereby pulling the carpet out under your own feet, so to say).

就这么简单

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

哦,别忘了完成后清除top.

Oh, and don't forget to clear top when you're done.

这篇关于无法弄清楚如何清除c ++中的链表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆