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

Asked

Viewed 813 times

3

I’d like to understand how the pop in batteries.

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

It turns out that that function my teacher passed the p points to n and this will only overwrite when used the push() and do not exclude the value. This is 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;
}
  • I don’t know if you know that you can vote for everything on the site as well as accept an answer to your questions. Check out the [tour] of the site.

1 answer

3


That’s right, the operation of pop on a stack has the function of returning the value that is at the top of the stack, as occurs in v and lower the battery indicator to the previous element. No need to erase the data, it gets there inaccessible (under normal conditions), after all you cannot access an element that is above the highest element of the valid stack.

Understand the pile as stacked boxes, the boxes are always there, if there is something in it is another matter. What matters is the pointer that says which is the tallest box.

When you give a push on the stack the value will be placed on the element that is above the highest current and will put in an existing box, which has a value there, but that doesn’t matter, you just put on top.

No need to clean up something that shouldn’t be accessed anymore. No other bureaucracies can be simple like this:

float pop(Pilha *p) { return p->vet[p->n--]; }

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.