Hi everone, I have been doing java for around a year now
I'm not looking for somebody to give me an answer but for guidance and help.
This is the question:
I have a stack called 's'.
push(s,m) -> pushes element n onto the stack .
pop(s) -> pops element from the stack s.
peek(s) -> return value of top element on the stack.
(Other info: may use other variables, a loop and/or second stack, s2)
Question = Set j to the third element of a stack leaving the stack unchanged.
This is my attempt:
I'm assuming there are two elements already on a stack as it doesn't say there should or shouldn't be!
Stack 1 : {m,n} -> (m being top element on stack)
push (s2, pop(s)) //This is supposed to pop the element on stack 1 sending it to stack 2 (s2)
Stack 1 : { n }
Stack 2 : { m }
push (s2, pop(s)) //pop element on stack 1, send to stack 2 again
stack 1 : { }
stack 2: { n,m}
push (s,j) //This pushes element j onto stack 1
stack 1 : { j }
stack 2: { n,m}
push (s, pop(s2)) // pops element on stack 2, pushing it back onto stack 1
stack 1 : { n,j }
stack 2: { m}
push (s, pop(s2)) // pops element on stack 2, pushing it again back onto stack 1
stack 1 : { m,n,j }
stack 2: { }
Stack 1 is now unchanged but has j set to the third element. Would you say this is correct?
Also is 'push (s, pop(s2))' the right format ??
Thanks for any help I would appreciate it so much, just trying to make sure i'm on the right lines