三合一
问题
三合一。描述如何只用一个数组来实现三个栈。
你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。
构造函数会传入一个stackSize参数,代表每个栈的大小。
代码
class TripleInOne {
vector<int> s;
int stackSize;
int spointer[3];
public:
TripleInOne(int stackSize) {
s = vector<int>(stackSize*3, 0);
this->stackSize = stackSize;
spointer[0] = 0;
spointer[1] = stackSize;
spointer[2] = stackSize*2;
}
void push(int stackNum, int value) {
if(spointer[stackNum] < (stackNum+1)*stackSize){
s[spointer[stackNum]++] = value;
}
}
int pop(int stackNum) {
int res = -1;
if(spointer[stackNum] > stackNum * stackSize){
res = s[--spointer[stackNum]];
}
return res;
}
int peek(int stackNum) {
int res = -1;
if(spointer[stackNum] > stackNum * stackSize){
res = s[spointer[stackNum]-1];
}
return res;
}
bool isEmpty(int stackNum) {
return spointer[stackNum] == stackNum*stackSize;
}
};
分析
对前置后置++的使用、vector、array的使用都很巧妙。
- 三个栈空的指针位置分别是0,stackSize,stackSize * 2 的位置(stackNum*stackSize)。
- 压栈操作,元素存入vector,指针会指向下一个元素的位置;
- 出栈操作,指针先前置减减,指针指向的是要弹出的元素,此时栈顶元素是指针前一个元素
- peek操作,指针位置不用改变,取出指针指向的前一个元素(栈顶元素)