3.1 Describe how you could use a single array to implement three stacks.
Approach 1: Fixed Division
class ThreeStack {
private:
int stackSize;
int *buffer;
int stackPointer[3];
public:
ThreeStack(int size) {
stackSize = size;
buffer = new int[stackSize*3];
for (int i = 0; i < 3; i++)
stackPointer[i] = -1;
}
~ThreeStack() {
delete[] buffer;
}
int absTopOfStack(int stackNum) {
return stackNum * stackSize + stackPointer[stackNum];
}
bool isEmpty(int stackNum) {
return stackPointer[stackNum] == -1;
}
int top(int stackNum) {
return buffer[absTopOfStack(stackNum)];
}
void push(int stackNum, int value) {
if (stackPointer[stackNum] + 1 >= stackSize) {
throw out_of_range("Out of space.");
}
stackPointer[stackNum]++;
buffer[absTopOfStack(stackNum)] = value;
}
int pop(int stackNum) {
if (stackPointer[stackNum] == -1) {
throw out_of_range("Trying to pop an empty stack.");
}
int value = buffer[absTopOfStack(stackNum)];
stackPointer[stackNum]--;
return value;
}
};
Approach 2: Flexible Divisions