Search code examples
cstackpeek

pop and peek doing same in that case?


From all the sources I've read, they say - the difference between peek and pop is that peek doesn't remove the top value. In the provided example from my lecture notes, apparently they do the same using a different method of subtraction. After both operations top has 1 subtracted.

Am I right? Probably not, can somebody explain how do those differ?

int pop(void)
{
    assert(top>0);
    return data[--top];
}
int peek(void)
{
    assert(top>0);
    return data[top-1];
}

Solution

  • top is a state variable for your stack, and in this case it is a stack which is stored in a regular array. The variable top references the top of the stack by storing an array index.

    The first operation, pop, uses the decrement operator to change the variable top. --top is equivalent to top = top - 1. And hence after a call to pop the state of the stack is also changed. The old value will remain in the array, but since the variable top now references a different index, this value is effectively removed: the top of the stack is now a different element. Now if you call a push, this popped value will be overwritten.

    The second operation doesn't change the value of the variable top, it only uses it to return the value at the top of the stack. The variable top still references the same value as the stack's top, and so the stack is unchanged.