Skip to content

Instantly share code, notes, and snippets.

@iwilbert
Created July 5, 2014 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwilbert/07aa98b1cccd43435eac to your computer and use it in GitHub Desktop.
Save iwilbert/07aa98b1cccd43435eac to your computer and use it in GitHub Desktop.
public class SetOfStack{
private ArrayList<Stack<Integer>> lstStack;
private int capacity;
public SetOfStack(int n) {
this.capacity = n;
this.lstStack = new ArrayList<Stack<Integer>>();
}
public void push(int val) {
if(lstStack.size() == 0 || lstStack.get(lstStack.size()-1).size() == capacity) {
Stack<Integer> stack = new Stack<Integer>();
lstStack.add(stack);
}
lstStack.get(lstStack.size()-1).push(val);
}
public int pop() {
if(lstStack.size() == 0) {
throw new NoSuchElementException("stack underflow!");
}
int idx = lstStack.size()-1;
Stack<Integer> stack = lstStack.get(idx);
int val = stack.pop();
if(stack.size() == 0)
lstStack.remove(idx);
return val;
}
public int popAt(int idx) {
if(lstStack.size() == 0)
throw new NoSuchElementException("stack underflow!");
if(idx >= lstStack.size())
throw new NoSuchElementException("stack overflow!");
Stack<Integer> stack = lstStack.get(idx);
int val = stack.pop();
if(stack.size() == 0)
lstStack.remove(idx);
return val;
}
}
@jason51122
Copy link

  1. Consider to move next element to current stack after pop() operation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment