100172. Three in One LCCI
2026/1/12大约 1 分钟约 430 字
100172. Three in One LCCI
难度: Easy
题目描述
Describe how you could use a single array to implement three stacks.
You should implement push(stackNum, value)、pop(stackNum)、isEmpty(stackNum)、peek(stackNum) methods. stackNumvalue is the value that pushed to the stack.
The constructor requires a stackSize parameter, which represents the size of each stack.
Example1:
Input: ["TripleInOne", "push", "push", "pop", "pop", "pop", "isEmpty"] [[1], [0, 1], [0, 2], [0], [0], [0], [0]] Output: [null, null, null, 1, -1, -1, true] Explanation: When the stack is empty, `pop, peek` return -1. When the stack is full, `push` does nothing.
Example2:
Input: ["TripleInOne", "push", "push", "push", "pop", "pop", "pop", "peek"] [[2], [0, 1], [0, 2], [0, 3], [0], [0], [0], [0]] Output: [null, null, null, null, 2, 1, -1, -1]
解题思路
代码实现
解决方案
java
class TripleInOne {
private Integer[][] stack;
private int stackSize;
public TripleInOne(int stackSize) {
this.stackSize = stackSize;
this.stack = new Integer[3][stackSize];
}
public void push(int stackNum, int value) {
if (stackNum < 0) {
return;
}
Integer[] data = stack[stackNum];
for (int i = 0; i < data.length; i++) {
if (data[i] == null) {
data[i] = value;
break;
}
}
}
public int pop(int stackNum) {
if (stackNum < 0) {
return -1;
}
Integer[] data = stack[stackNum];
for (int i = data.length - 1; i > -1; i--) {
if (data[i] != null) {
int res = data[i];
data[i] = null;
return res;
}
}
return -1;
}
public int peek(int stackNum) {
if (stackNum < 0) {
return -1;
}
Integer[] data = stack[stackNum];
for (int i = data.length - 1; i > -1; i--) {
if (data[i] != null) {
int res = data[i];
return res;
}
}
return -1;
}
public boolean isEmpty(int stackNum) {
if (stackNum < 0) {
return true;
}
Integer[] data = stack[stackNum];
if(data==null|| data.length==0){
return true;
}
return data[0] == null;
}
}
/**
* 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);
*/