"Implement" generally means write, pure and simple. Your educator wants you to write code that can do what the assignment says.
Stacks of fixed size (n
) can be easily implemented as an array with a current stack depth but you have an extra twist to your assignment inasmuch as you're only alowed to have n
elements on both stacks combined rather than each stack.
I would implement it as follows (pseudo-code only since it's homework and, in any case, you haven't specified a language):
# Create the two stacks, each of size sz.
init_stack (sz):
allocate stack1 as array[1 to sz] of integer
allocate stack2 as array[1 to sz] of integer
set stack1sz to 0
set stack2sz to 0
set maxsz to sz
# Push the value val onto stack stk.
push_stack (stk,val):
if stk is not equal to 1 or 2:
return error
if stack1sz + stack2sz is equal to maxsz:
return error
if stk is 1:
add 1 to stack1sz
set element stack1sz of stack1 to val
else:
add 1 to stack2sz
set element stack2sz of stack2 to val
# Pop a value off stack stk.
pop_statkck (stk):
if s is not equal to 1 or 2:
return error
if stk is 1:
if stack1sz is 0:
return error
set val to element stack1sz of stack1
subtract 1 from stack1sz
else:
if stack2sz is 0:
return error
set val to element stack2sz of stack2
subtract 1 from stack2sz
return val
The variables stack1
, stack2
, stack1sz
, stack2sz
and maxsz
should be declared in such a way that they survive in between function calls (i.e., not locals). All others are transitory.
If you have troubles converting that to a specific language, leave a comment and I'll provide pointers on what to look for.