How does the "pop ()" function work on a stack?

3

I would like to understand how pop works in stacks.

I just put the part that I did not understand, I know that in the pop() function there is also the empty check, but I only put the part that I did not understand.

It turns out that this function that my teacher passed p points to n and this will only overwrite when push() is used and not delete the value. Is that correct?

define MAX = 50;

struct Pilha {
    int n;
    float vet[MAX];
}

float pop(Pilha *p) {
    float v;

    v = p->vet[p->n];
    p->n--;
    return v;
}
    
asked by anonymous 31.08.2018 / 20:47

1 answer

3

That's correct, the pop operation on a stack is to return the value that is on the top of the stack, as in v , and lower the stack indicator to the previous element. There is no need to erase the data, it is there inaccessible (under normal conditions), after all you can not access an element that is above the highest element of the valid stack.

Understand the stack as stacked boxes, the boxes are always there, if there is anything inside it is another matter. What matters is the pointer that says which is the tallest box.

When you give a push in the stack, the value will be placed in the element that is above the current high and put in an existing box, which has a value there, but that does not matter, you only put it over.

You do not need to clean something that should not be accessed any more. No other bureaucracy can be simple like this:

float pop(Pilha *p) { return p->vet[p->n--]; }
    
31.08.2018 / 20:58