user7118152 user7118152 - 1 year ago 134
C++ Question

How to build a C++ Stack structure

struct Node{
int value;
Node *next;
Node(int val) :value(val), next(nullptr){}
class Stack
void push(int val);
int pop();
bool is_empty(){ return first == nullptr; }
Node *first = nullptr;

int Stack::pop(){
int ret = first->value;
first = first->next;
return ret;
void Stack::push(int i){
if (is_empty()){
first = &Node(i);
Node oldFirst = *first;
first = &Node(i);
first->next = &oldFirst;

Here is how I wrote the code, however, there is a problem that when I finished
the pointer of
isn't point to the right object. I'm wondering how I can solve that problem.

Answer Source

The expression &Node(i) creates a temporary object and give you a pointer to it. And then the temporary object is immediately destructed, leaving you with a pointer to a non-existing object.

You need to use new to allocate a new object.

You have a similar problem with &oldFirst, which give you a pointer to a local variable, which will be destructed once the function returns. You need to use a pointer variable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download