# Can somebody help me with stacks?

• 10-08-2012, 03:32 PM
sim18
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)

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
• 10-08-2012, 03:41 PM
KevinWorkman
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.
• 10-08-2012, 07:01 PM
sim18
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?
• 10-08-2012, 07:06 PM
KevinWorkman
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.