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];
}
Peek simply returns the value of what is on top of the stack. In contrast to this, pop will remove the value from the stack and then return it. To do this, we first get the value of the top and store it. From here, we set the top to be the next node that follows it, and returns the value that was removed.
This method returns the top element from the stack without deleting it from the stack. The only difference between peek and pop is that the peek method just returns the topmost element; however, in the case of a pop method, the topmost element is returned and also that element is deleted from the stack.
peek() & top() functions are same but peek() is unavailable in std::stack . You can check it here- http://www.cplusplus.com/reference/stack/stack/ . Actually, peek() and top() both take O(1) time without any other queries.
The peek() method of Queue Interface returns the element at the front the container. It does not deletes the element in the container. This method returns the head of the queue. The method does not throws an exception when the Queue is empty, it returns null instead.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With