Skip to content

Instantly share code, notes, and snippets.

@jingz8804
Last active August 29, 2015 14:03
Show Gist options
  • Save jingz8804/832ecc1beee6f0ed6899 to your computer and use it in GitHub Desktop.
Save jingz8804/832ecc1beee6f0ed6899 to your computer and use it in GitHub Desktop.
#ctci
import java.util.ArrayList;
import java.util.Stack;
public class SetOfStacks<E>{
private int numOfStacks;
private ArrayList<Stack<E>> stacks;
private int capacity;
public SetOfStacks(int capacity){
this.capacity = capacity;
stacks = new ArrayList<Stack<E>>();
Stack<E> s = new Stack<E>();
numOfStacks++;
}
public void push(E val){
Stack<E> s = stacks.get(numOfStacks-1);
if(s.size() == capacity){
Stack<E> newS = new Stack<E>();
s = newS;
stacks.add(newS);
numOfStacks++;
}
s.push(val);
}
public E pop() throws Exception{
if(numOfStacks == 0) throw new Exception("Stack underflow!");
Stack<E> s = stacks.get(numOfStacks-1);
E val = s.pop();
if(s.size() == 0){
stacks.remove(numOfStacks-1);
numOfStacks--;
}
return E;
}
public E popAt(int index) throws Exception{
if(numOfStacks == 0) throw new Exception("Stack underflow!");
if(numOfStacks <= index) throw new Exception("No such stack exists!");
Stack<E> s = stacks.get(index);
E val = s.pop();
if(s.size() == 0){
stacks.remove(index);
numOfStacks--;
}
return E;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment