Created
January 30, 2016 12:56
-
-
Save berkayk/e4fde1282515b1fa7dfd to your computer and use it in GitHub Desktop.
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
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