문제

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];
}
도움이 되었습니까?

해결책

top is a state variable for your 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, and hence the state of the stack: --top is equivalent to top = top - 1. The value is still 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.

다른 팁

They will return the same value but only pop changes top:

--top

this is equivalent to

top = top -1

where as top - 1 does not change the value of top.

In general programming terms, "pop" means the method of returning an object from a stack, while at the same time removing it from the stack. The term "peek" is more generic and can be used on other data containers/ADTs than stacks. "Peek" always means "give me the next item but do not remove it from the container".

Most often "peek" is used together with queue-like data containers, for example the Windows API function for checking the next message in the windows message queue is named PeekMessage().

This

return data[--top];

changes the value of top while this

return data[top-1];

does not change it. Thus, when you call pop the pointer to the top of the stack is modified to point to a new item while peek leaves the pointer unchanged so the functions behave in the correct sense you describe

In pop its doing --top which is top=top-1 so it changes the value of top.

While in peek, its doing top-1 i.e. just decrements top by 1 and use the value, top is unchanged.

Function of pop - It extracts the top element and move to the next before it.so the pointer now moved to the next element.top element position is now decrease by 1.

Function of peek - It only return the top element but the pointer is still there. so the top element position remain unchanged.

actually pop and peak are same but the thing is the former saw the data and closed the box but the later first took the data saw it and closed the box

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top