c++ - Stack中的无限循环,实现为 "Linked List"

标签 c++ for-loop linked-list stack

请看下面的代码

#include <iostream>

using namespace std;

class Stack
{
public:
    Stack();
    ~Stack();

    void push(void *data);
    void *pop();
    void print();

protected:
    typedef struct Element
    {
        struct Element *next;
        void *data;

    }Element;

    Element *top;
};

Stack::Stack()
{
    top = NULL;
}

Stack::~Stack()
{
    while(top)
    {
        Element *elm = top->next;
        delete top;
        top = elm;
    }
}

void Stack::push(void *data)
{
    Element *elm = new Element;
    elm->data = data;
    elm->next = top;;
    top = elm;
}

void *Stack::pop()
{
    void *data;

    if(top==NULL) return data;

    data = top->data;

    Element *elm = top;

    top = elm->next;
    delete elm;
    return data;


}

void Stack::print()
{
    Element *elm = top;

    while(elm)
    {
        cout << *(static_cast<int *>(elm->data))<<" ";
        elm = elm->next;
    }

    cout << endl;
}

int main()
{
    Stack *st = new Stack;;

    int n1 = 10;
    int n2 = 20;
    int n3 = 30;
    int n4 = 40;
    int n5 = 50;

    st->push(&n1);
    st->push(&n2);
    st->push(&n3);
    st->push(&n4);
    st->push(&n5);
    st->print();

    cout << *(static_cast<int*>(st->pop()))<< " poped\n";
    cout << *(static_cast<int*>(st->pop()))<< " poped\n";

    st->print();

    cout << endl;

    system("pasue");
    return 0;
}

其实我在学习这个数据结构就是这样实现的,这是我的第一次尝试。为什么会进入死循环?

最佳答案

问题是:

void *Stack::pop()
{
    void *data;
    //...
}

使用前初始化变量:

void *Stack::pop()
{
    void *data = NULL;
    //...
}

如果将 pop 方法放在一个循环中以提取所有元素,它可能永远不会返回 NULL,因为未初始化的变量可以有任何值(内存中的任何值)之前的位置)。

关于c++ - Stack中的无限循环,实现为 "Linked List",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050691/

相关文章:

c++ - 内存管理 : Returning a vector element and deleting(pop_back) it

c++ - C++仿函数行为

c++ - 动态设置 for 循环的初始化、条件和 in/decrementation

python - 使用一行代码打印一个for循环

java - 方法中多个 LinkedList 对象的工作

c++ - 使用c++根据第一个数组中的元素对第二个数组进行排序并删除一些元素

c++ - 如何在 C++ 程序中捕获 strace 的输出

python - 类型错误 : object of type 'NoneType' has no len() while iterating through a list

将 poll() 应用于 LinkedList 时发生 Java 错误

algorithm - 在链表中检测循环开始的证明