File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 1+ import java.util.*;
2+
3+ class MinStack {
4+ Stack<Integer> stack = new Stack<>();
5+ Stack<Integer> minStack = new Stack<>();
6+
7+ void push(int val){
8+ if(minStack.isEmpty() || val<=minStack.peek()){
9+ minStack.push();
10+ }
11+ }
12+
13+ void pop(){
14+ if(!stack.isEmpty()){
15+ if(minStack.peek()==stack.peek()){
16+ minStack.pop();
17+ }
18+ else{
19+ stack.pop();
20+ }
21+ }
22+ }
23+
24+ int top(){
25+ return stack.isEmpty() ? -1 : stack.peek();
26+ }
27+
28+ int getMin(){
29+ return stack.isEmpty() ? -1 : minStack.peek();
30+ }
31+
32+ public static void main(String[] args){
33+ Scanner input = new Scanner(System.in);
34+ MinStack stkimp = new MinStack();
35+ int operations = input.nextInt();
36+ for(int i = 0; i<operations; i++){
37+ String op = input.next();
38+
39+ switch(op){
40+ case "push":
41+ int val = input.nextInt();
42+ stkimp.push(val);
43+
44+ case "pop":
45+ stkimp.pop();
46+
47+ case "top":
48+ stkimp.top();
49+
50+ case "getMin":
51+ stkimp.getMin();
52+ }
53+ }
54+ }
55+ }
You can’t perform that action at this time.
0 commit comments