题目:
三合一。描述如何只用一个数组来实现三个栈。
你应该实现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]
分析:
开辟数组的大小为stackNum*3+3,平分数组作为三个栈存储的空间,额外再给三个位置用来记录每个栈存储元素的个数,就用,数组中最后三个索引,array[size- 0]表示第一个栈,array[size- 1]表示第二个栈,array[size- 2]表示第三个栈,正好对应每个栈的序号。
程序:
class TripleInOne {
public TripleInOne(int stackSize) {
stack = new int[stackSize * 3 + 3];
}
public void push(int stackNum, int value) {
int size = stack.length - 3;
if(stack[stack.length - stackNum - 1] >= (size / 3))
return;
int index = stackNum * (size / 3);
stack[index + stack[stack.length - stackNum - 1]] = value;
stack[stack.length - stackNum - 1]++;
}
public int pop(int stackNum) {
int size = stack.length - 3;
if(stack[stack.length - stackNum - 1] <= 0)
return -1;
int index = stackNum * (size / 3) + stack[stack.length - stackNum - 1] - 1;
int res = stack[index];
stack[stack.length - stackNum - 1]--;
return res;
}
public int peek(int stackNum) {
int size = stack.length - 3;
if(isEmpty(stackNum))
return -1;
int index = stackNum * (size / 3) + stack[stack.length - stackNum - 1] - 1;
int res = stack[index];
return res;
}
public boolean isEmpty(int stackNum) {
return stack[stack.length - stackNum - 1] == 0;
}
private int[] stack;
}
/**
* 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);
*/
来源:https://www.cnblogs.com/silentteller/p/12410276.html