1

请看下面的代码

#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;
}

实际上,我正在学习这种数据结构以这种方式实现,这是我的第一次尝试。为什么会进入无限循环?

4

2 回答 2

2

这是问题所在:

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

使用前初始化变量:

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

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

于 2013-02-24T10:15:29.567 回答
1

You are returning garbage value

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

    if(top==NULL) return data;

At this if(top==NULL) return data; data points garbage
You should return NULL

if(top==NULL) return top;
于 2013-02-24T10:18:00.810 回答