Created
July 6, 2014 18:57
-
-
Save hilda8519/7963ed7fe23fdc513dfd 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
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