[Solved] reason why it doesn’t works on visual 2019


In your constructor

Stack() {
    top->next = NULL;
}

top has never been given a value, so top->next is an error.

Looks to me that most of your code would be fixed if you replaced top->next with top throughout.

There’s another error here

void Stack::show() {
    Node *cur = new Node;
    cur = top-> next;

You assign cur to a new node and then you forget about that and assign it to something else on the very next line. Just do this

void Stack::show() {
    Node *cur = top-> next;

(but top-> next should really just be top as explained above).

and the same error here

Node *temp = new Node;

temp = top->next;

why assign a new node to temp if on the very next line you assign something else to temp?

Here’s your code will all the bugs fixed (I think)

class Stack {
    public:
    Node *top;
    Stack() {
        top = NULL;
    }
    void push(int data);
    int pop();
    void show();
};
void Stack::push(int data)
{
    Node *node = new Node;
    node->data = data;
    node->next = top;
    top = node;
}
int Stack::pop()
{
    if (top == NULL) {
        cout << "stack empty" << endl;
        return 0;
    }
    Node *temp = top;
    int data = temp->data;
    top = temp->next;
    delete temp;
    return data;
}

void Stack::show() {
    Node *cur = top;
    while (cur != NULL) {
        cout << cur-> data << "->";
        cur = cur-> next;
    }

}

solved reason why it doesn’t works on visual 2019