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