Skip to content

Instantly share code, notes, and snippets.

@hilda8519
Created July 6, 2014 18:57
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 hilda8519/7963ed7fe23fdc513dfd to your computer and use it in GitHub Desktop.
Save hilda8519/7963ed7fe23fdc513dfd to your computer and use it in GitHub Desktop.
import java.util.Stack;
public class StackWithMin extends Stack<Integer>{
Stack<Integer> s2;
public StackWithMin(){
s2=new Stack<Integer>();
}
public void push(int value){
if(value<=min()){
s2.push(value);
}
super.push(value);
}
public Integer pop(){
int value=super.pop();
if(value==min()){
s2.pop();
}
return value;
}
public int min(){
if(s2.isEmpty()){
return Integer.MAX_VALUE;
}
else{
return s2.peek();
}
}
public static void main(String[] args) {
StackWithMin stack = new StackWithMin();
for(int i = 0; i < 10; i++) {
stack.push(10 - i);
}
while(!stack.isEmpty()) {
System.out.println("current min elem is " + stack.min());
System.out.println("top elem is " + stack.pop());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment