import java.util.Stack;
public class MinimumFromStack {
public static void main(String[] args) {
Stack<Pair> stack = new Stack<>();
Pair pair = new Pair(5,stack);
stack.add(pair);
Pair pair1 = new Pair(9,stack);
stack.add(pair1);
Pair pair2 = new Pair(7,stack);
stack.add(pair2);
Pair pair3 = new Pair(6,stack);
stack.add(pair3);
Pair pair4 = new Pair(3,stack);
stack.add(pair4);
System.out.println("Smallest element in stack : " + stack.peek().getMinimum());
System.out.println("Top element in stack : " + stack.peek().getActual());
System.out.println("removing Top element in stack : " + stack.pop());
System.out.println("Smallest element in stack : " + stack.peek().getMinimum());
}
private static class Pair {
int actual;
int minimum;
Pair(int actual,Stack<Pair> stack){
this.actual =actual;
this.minimum = stack.isEmpty() ? actual : Math.min(actual,stack.peek().getMinimum());
}
public int getActual() {
return actual;
}
public int getMinimum() {
return minimum;
}
}
}
No comments:
Post a Comment