Skip to content

Instantly share code, notes, and snippets.

@berkayk
Created January 30, 2016 12:56
Show Gist options
  • Save berkayk/e4fde1282515b1fa7dfd to your computer and use it in GitHub Desktop.
Save berkayk/e4fde1282515b1fa7dfd to your computer and use it in GitHub Desktop.
public class StackWithMin extends Stack<Integer> {
Stack<Integer> minStack;
private int minValue;
public StackWithMin() {
super();
minStack = new Stack<Integer>();
}
public Integer getMin() {
if (minStack.isEmpty())
return Integer.MAX_VALUE;
return minStack.peek(); // get top
}
public void push(int data) {
super.push(data);
if (this.isEmpty()) {
minValue = data;
minStack.push(data);
}
else {
if (data < minValue) {
minValue = data;
minStack.push(data);
}
}
}
public Integer pop() {
if (this.isEmpty())
return null;
int value = super.pop();
if (value == getMin()) {
minStack.pop();
}
return value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment