The data structure question I was trying to solve is as follows:
Stack of Plates:
Imagine a (literal) stack of plates. If the stack gets too high, it might topple. Therefore, in real life, we would likely start a new stack when the previous stack exceeds some threshold. Implement a data structure
SetOfStacksthat mimics this.SetOfStacksshould be composed of several stacks and should create a new stack once the previous one exceeds capacity.SetOfStacks.push()andSetOfStacks.pop()should behave identically to a single stack (that is,pop()should return the same values as it would if there were just a single stack).
I am trying to practice better data structure design, so I was looking for some feedback on my code as well as tips for going forward:
import java.util.*;
public class StackOfPlates {
public class StackNode {
private int data;
public StackNode(int d){
data = d;
}
public int getData(){
return data;
}
}
List<ArrayList<StackNode>> setOfStacks;
private int stackCapacity;
public StackOfPlates(int c){
setOfStacks = new ArrayList<ArrayList<StackNode>>();
stackCapacity = c;
}
void push(int item){
StackNode s = new StackNode(item);
if(setOfStacks.isEmpty()){
ArrayList<StackNode> st = new ArrayList<StackNode>();
st.add(s);
setOfStacks.add(st);
}
else{
int index = setOfStacks.size() - 1;
int currStackSize = setOfStacks.get(index).size();
if(currStackSize == stackCapacity){
ArrayList<StackNode> st = new ArrayList<StackNode>();
st.add(s);
setOfStacks.add(st);
setOfStacks.get(index + 1).add(s);
}
else{
setOfStacks.get(index).add(s);
}
}
}
StackNode pop(){
int setOfStacksSize = setOfStacks.size();
if(setOfStacksSize == 0) return null;
ArrayList<StackNode> lastStack = setOfStacks.get(setOfStacksSize - 1);
int lastElmtIndex = lastStack.size() - 1;
StackNode end = lastStack.get(lastElmtIndex);
lastStack.remove(lastElmtIndex);
return end;
}
}