Skip to content

Instantly share code, notes, and snippets.

@st0le
Created April 28, 2013 19:34
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 st0le/5478107 to your computer and use it in GitHub Desktop.
Save st0le/5478107 to your computer and use it in GitHub Desktop.
Stack with Min()
class StackMin extends Stack {
private Stack minStack;
public StackMin(int size) {
super(size);
minStack = new Stack(size);
}
@Override
public void push(int item) throws Exception {
if(empty() || item <= minStack.peek())
minStack.push(item);
super.push(item);
}
@Override
public int pop() throws Exception {
int item = super.pop();
if(item == minStack.peek())
minStack.pop();
return item;
}
public int min() throws Exception {
if(empty()) throw new Exception("Stack is empty.");
return minStack.peek();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment