Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pop and peek doing same in that case?

Tags:

c

stack

peek

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];
}
like image 781
Peter Cerba Avatar asked Sep 14 '12 19:09

Peter Cerba


People also ask

What is the difference between peek and pop?

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.

What is the difference between the stack method peek and pop?

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.

Is peek and top the same Java?

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.

What will happen if peek () operation is performed in queues?

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.


1 Answers

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.

like image 80
pb2q Avatar answered Sep 22 '22 22:09

pb2q