I'm preparing for an interview so I'm trying to solve some problems to stretch my mind. Here is one:
Describe how you could use a single array to implement three stacks.
And here is my implementation:
class StackUnderflowError extends RuntimeException {
public StackUnderflowError(String msg) {
super(msg);
}
}
class ThreeStacks<T>{
private T[] array;
private int firstIndex = 0;
private int secondIndex = 1;
private int thirdIndex = 2;
public ThreeStacks(Class<T> classT, int capacity) {
array = (T[])Array.newInstance(classT, capacity);
}
void push(T data, int stack){ //enum to select the stack
switch(stack)
{
case 1: pushOne(data);
break;
case 2: pushTwo(data);
break;
case 3: pushThree(data);
break;
default: throw new IllegalArgumentException("stack");
}
}
T pop(int stack){
switch(stack){
case 1: return popOne();
case 2: return popTwo();
case 3: return popThree();
default: throw new IllegalArgumentException("stack");
}
}
private void pushOne(T data) {
if (firstIndex > array.length - 1) {
throw new StackOverflowError("firstStack");
} else{
array[firstIndex] = data;
firstIndex += 3;
}
}
private void pushTwo(T data) {
if (secondIndex > array.length - 1) {
throw new StackOverflowError("secondStack");
} else{
array[secondIndex] = data;
secondIndex += 3;
}
}
private void pushThree(T data) {
if (thirdIndex > array.length - 1) {
throw new StackOverflowError("thirdStack");
} else{
array[thirdIndex] = data;
thirdIndex += 3;
}
}
private T popOne() {
firstIndex -= 3;
if(firstIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[firstIndex];
}
private T popTwo() {
secondIndex -= 3;
if(secondIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[secondIndex];
}
private T popThree() {
thirdIndex -= 3;
if(thirdIndex < 0){
throw new StackUnderflowError("fristStack");
}
return array[thirdIndex];
}
}
And test:
ThreeStacks<String> threeStacks = new ThreeStacks<>(String.class, 1024);
threeStacks.push("1", 1);
threeStacks.push("2", 2);
threeStacks.push("3", 3);
threeStacks.push("4", 1);
threeStacks.push("5", 2);
threeStacks.push("6", 3);
System.out.println( threeStacks.pop(1) );
System.out.println( threeStacks.pop(2) );
System.out.println( threeStacks.pop(2) );
System.out.println( threeStacks.pop(1) );
//System.out.println( threeStacks.pop(1) );
How can I improve this? A few thoughts:
- use array instead of switch (stacks' indexes)
- use enum to choose stack
- use ArrayList (if interviewer agrees)
break
in yourswitch
\$\endgroup\$