请查看以下代码
#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;
}
实际上,我正在学习这种以这种方式实现的数据结构,这是我的第一次尝试。为什么它会进入无限循环?
答案 0 :(得分:2)
问题在于:
void *Stack::pop()
{
void *data;
//...
}
在使用前初始化变量:
void *Stack::pop()
{
void *data = NULL;
//...
}
如果将pop
方法放在循环中以提取所有元素,它可能永远不会返回NULL
,因为未初始化的变量可以具有任何值(之前在内存位置中的任何值)。
答案 1 :(得分:1)
您正在返回垃圾值
void *Stack::pop()
{
void *data;
if(top==NULL) return data;
在此if(top==NULL) return data;
数据点垃圾
你应该返回NULL
if(top==NULL) return top;