编辑2:程序正在运行。谢谢您的帮助 最后一个问题: 我在每次推送时都会分配内存。如果我想在pop中删除它,这段代码会起作用吗?
int pop()
{
cout << "About to pop: " << top->getData() << "\n";
int retVal = top->getData();
if(top->getLasty()!=NULL)
{
node* temp = top;
top = top->getLasty();
delete temp;
cout << "new data is: " << top->getData() << "\n";
}
return retVal;
}
};
工作代码:
#include <iostream>
using namespace std;
class node
{
int data;
node* lasty;
public:
node()
{
lasty = NULL;
data = -1;
}
node(node* ptr,int dat)
{
lasty = ptr;
data = dat;
cout << "New node created! Data is " << dat << ", lasty's data is " << ptr->getData() << "\n";
}
node* getLasty()
{
return lasty;
}
int getData()
{
return data;
}
void setData(int x)
{
data = x;
}
void setLasty(node* ptr)
{
lasty = ptr;
}
};
class stack
{
node* top;
public:
stack()
{
cout << "New Stack created!\n";
top = new node();
}
~stack()
{
delete top;
}
void push(int x)
{
cout << "Before pushing, top's data is " << top->getData() << "\n";
top = new node(top, x);
//node* temp = new node();
//temp->setData(x);
//temp->setLasty(top);
//top = temp;
cout << "TOP'S DATA IS: " << top->getData() << "\n";
cout << "TOP: " << "top lasty's data is: " << top->getLasty()->getData() << "\n\n";
}
int pop()
{
cout << "About to pop: " << top->getData() << "\n";
int retVal = top->getData();
if(top->getLasty()!=NULL)
{
top = top->getLasty();
cout << "new data is: " << top->getData() << "\n";
}
return retVal;
}
};
int main()
{
stack a;
a.push(1);
a.push(2);
a.push(3);
cout << a.pop();
cout << a.pop();
return 0;
}
同样结果我需要更多文字来提交此编辑,因此请考虑这个填充文字。
答案 0 :(得分:1)
stack()
{
cout << "New Stack created!\n";
node a = node();
top = &a;
}
节点a
是局部变量,因此在传递构造函数体后会被销毁。然后指针top
引用被破坏的对象。您应该在堆中创建它并在以后删除它。
stack()
{
cout << "New Stack created!\n";
top = new Node();
}
答案 1 :(得分:0)
另一个问题:
node(node ptr,int dat)
{
lasty = &ptr;
data = dat;
cout << "New node created! Data is " << dat << ", lasty's data is " << ptr.getData() << "\n";
}
您正在获取复制变量的地址。传递ptr
时,编译器正在制作原始项的副本。这称为按值传递。
由于变量的名称是ptr
,我假设您正在传递指向节点的指针。您应该指定指针的值,而不是其地址:
// Original
// lasty = &ptr;
// Assigning the pointer value:
lasty = ptr;
// Notice removal of `&`.
您可以指定指针指针。