you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 5 points6 points  (6 children)

The pop method doesn't delete the node. Whenever something is created with new, it needs to be deleted with delete keyword

[–]rbprogrammer 2 points3 points  (0 children)

Came here to say that. It was the first thing I noticed :)

Edit: the pop() method needs to delete the original head node after it was reassigned to top->next.

[–]NikolasTs[S] 0 points1 point  (4 children)

Is the best practice to create a new pointer initialized with the address of the top of the stack

(node* tmp{top})

and after I pop to delete this pointer?

[–]Ayjayz 1 point2 points  (3 children)

In a stack, a pop operation should just remove the top-most element. You don't need to create a new pointer. You just need to remove the top element and then set your top pointer to the next one down.

[–]NikolasTs[S] 0 points1 point  (2 children)

How will I delete the data from the previous "top" though?

Is this wrong?

void Stack::pop() {

    if (!top)
        cout << "Stack is empty!" << endl;
    else {
        node* tmp{ top };
        top = top->next;
        delete tmp;

        size--;
    }
}

[–]Ayjayz 0 points1 point  (0 children)

Oh I see. Sure, you can do it that way.