Can somebody help me with stacks?

Hi, I get the concept of what a stack does and i know what pop(), push(), peek() and isEmpty() means.

I have a stack called 't'.

push(t,n) -> pushes element n onto the stack t.

pop(t) -> pops element from the stack t.

peek(t) -> return value of top element on the stack.

(Other info: may use other variables, a loop and/or second stack, t2)

There has bee one question already done for us :

set 'h' to the second element of a stack leaving the stack without its top element.

__Answer: pop(s) and h = peek(s)__

Please could somebody explain how they get to this answer?

I will try and explain how I see it:

So it says set h to the second element of the stack, this is assuming there is already 1 element at the top. So to me it says pop(s)the first element in the stack 's' and then h = peek(s) - returns h to the top element of the stack. I don't see how that could be the answer as its not the second element?

Thanks for anybody who can help

Re: Can somebody help me with stacks?

What do you mean when you say that this:

h = peek(s);

...returns h to the top element of the stack?

It's not adding anything to the stack. I'd suggest drawing out a few example of a stack and performing the actions you described on it, drawing out the results of each step.

Re: Can somebody help me with stacks?

Yes I assume thats what it means, but if that returned it to the top of the stack, how could it be the second element in the stack?

Re: Can somebody help me with stacks?

Quote:

Originally Posted by

**sim18** Yes I assume thats what it means, but if that returned it to the top of the stack, how could it be the second element in the stack?

Like I said, draw out some example stacks and perform the operations on it. Start with {1, 2, 3}. What is the second element in the stack? What happens when you perform the operations on it?

The question is worded a little strangely, leaving it a bit unclear which operation should come first, but from the context of the answer you can tell what the intention is.