1、思路
-
用一个矩阵实现三个栈,那么将一个矩阵分成三等份即可;
-
矩阵的三个部分分别做好编号,栈1:
[0, n/3)
,栈2:[n/3, 2n/3)
,栈3:[2n/3,n)
。
2、代码
class TripleInOne {
private:
int numberOfStacks = 3; //一共有3个栈
int stackCapacity;
vector<int> sizes; //存放每个栈的当前元素个数
vector<int> values;
public:
TripleInOne(int stackSize) {
stackCapacity = stackSize;
sizes.resize(3);
values.resize(numberOfStacks * stackSize);
}
void push(int stackNum, int value) {
if (!isFull(stackNum))
{
sizes[stackNum] ++ ;
values[indexOfTop(stackNum)] = value;
}
}
int pop(int stackNum) { //弹出指定栈顶元素并返回其值
if (!isEmpty(stackNum))
{
int topIndex = indexOfTop(stackNum);
int value = values[topIndex];
values[topIndex] = 0;
sizes[stackNum] -- ;
return value;
}
return -1;
}
int peek(int stackNum) {
if (!isEmpty(stackNum))
{
return values[indexOfTop(stackNum)];
}
return -1;
}
bool isEmpty(int stackNum) { //判断栈是否为空
return sizes[stackNum] == 0;
}
bool isFull(int stackNum) //判断栈是否满了
{
return sizes[stackNum] == stackCapacity;
}
//取得指定栈的栈顶元素所在数组中的下标
int indexOfTop(int stackNum)
{
return stackNum * stackCapacity + sizes[stackNum] - 1;
}
};