三合一。描述如何只用一个数组来实现三个栈。
你应该实现push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum)方法。stackNum表示栈下标,value表示压入的值。
构造函数会传入一个stackSize参数,代表每个栈的大小。
示例1:
输入:
[“TripleInOne”, “push”, “push”, “pop”, “pop”, “pop”, “isEmpty”]
[[1], [0, 1], [0, 2], [0], [0], [0], [0]]
输出:
[null, null, null, 1, -1, -1, true]
说明:当栈为空时pop, peek
返回-1,当栈满时push
不压入元素。
示例2:
输入:
[“TripleInOne”, “push”, “push”, “push”, “pop”, “pop”, “pop”, “peek”]
[[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]]
输出:
[null, null, null, null, 2, 1, -1, -1]
java代码:
class TripleInOne{
public int[] a;
private int stackSize;
private int index1,index2,index3;
public TripleInOne(int stackSize) {
this.stackSize = stackSize;
a = new int[stackSize * 3];
index1 = -1;// [0,stackSize)
index2 = stackSize - 1;//[stackSize,stackSize*2)
index3 = stackSize * 2 - 1 ;//[stackSize*2,stackSize*3)
for (int i = 0; i < a.length; i++) {
a[i] = -1;
}
}
public void push(int stackNum, int value) {
if (stackNum == 0){
if (index1+1 < stackSize){
index1++;
a[index1] = value;
}else{
return;
}
}
if (stackNum == 1){
if (index2+1 < stackSize*2){
index2++;
a[index2] = value;
}else{
return;
}
}
if (stackNum == 2){
if (index3+1 < stackSize*3){
index3++;
a[index3] = value;
}
}
}
public int pop(int stackNum) {
if (stackNum == 0 && index1 >= 0){
index1--;
return a[index1+1];
}
if (stackNum == 1 && index2 >= stackSize){
index2--;
return a[index2+1];
}
if (stackNum == 2 && index3 >= stackSize*2){
index3--;
return a[index3+1];
}
return -1;
}
public int peek(int stackNum) {
int result = -1;
if (stackNum == 0 && index1 >= 0){
result = a[index1];
}
if (stackNum == 1 && index2 >= stackSize){
result = a[index2];
}
if (stackNum == 2 && index3 >= stackSize*2){
result = a[index3];
}
return result;
}
public boolean isEmpty(int stackNum) {
if (stackNum == 0 && index1 == -1){
return true;
}
if (stackNum == 1 && index2 == stackSize-1){
return true;
}
if (stackNum == 2 && index3 == stackSize*2-1){
return true;
}
return false;
}
}
/**
* Your TripleInOne object will be instantiated and called as such:
* TripleInOne obj = new TripleInOne(stackSize);
* obj.push(stackNum,value);
* int param_2 = obj.pop(stackNum);
* int param_3 = obj.peek(stackNum);
* boolean param_4 = obj.isEmpty(stackNum);
*/