Exercise 10.1-2

Explain how to implement two stacks in one array \(A[1...n]\) in such a way that neither stack overflows unless the total number of elements in both stacks together is \(n\). The PUSH and POP operations should run in \(O(1)\) time.

Have one stack begin at \(A[1]\) with the top position increasing when values are pushed and decreasing on the POP operation.

Have the second stack begin at \(A[n]\) with the top position decreasing when values are pushed and increasing on the POP operation.

Finally, have the array throw a stack overflow error when a PUSH operation would cause both top values to be equal.