Describe how you could use a single array to implement three stacks.
就是把数组平均分三段,本质是数组模拟栈,加上段偏移即可。
class array_stack
{
private:
int *buf;
int ptop[3];
int size;
public:
array_stack(int size = 300)
{
buf = new int[size*3];
ptop[0]=ptop[1]=ptop[2]=-1;
this->size = size;
}
~array_stack()
{
delete[] buf;
}
void push(int stackNum, int val)
{
int index = stackNum*size + ptop[stackNum] + 1;
buf[index] = val;
ptop[stackNum]++;
}
void pop(int stackNum)
{
ptop[stackNum]--;
}
int top(int stackNum)
{
int index = stackNum*size + ptop[stackNum];
return buf[index];
}
bool isEmpty(int stackNum)
{
return ptop[stackNum]==-1;
}
};