Created
April 28, 2013 19:34
-
-
Save st0le/5478107 to your computer and use it in GitHub Desktop.
Stack with Min()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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