File tree 1 file changed +58
-0
lines changed
1 file changed +58
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java .util .Stack ;
2
+
3
+ class MinStack {
4
+ Stack <Integer > st = new Stack <>();
5
+ Stack <Integer > min = new Stack <>();
6
+
7
+ public MinStack () {}
8
+
9
+ public void push (int val ) {
10
+ st .push (val );
11
+ if (min .isEmpty () || val <= min .peek ()) {
12
+ min .push (val );
13
+ } else {
14
+ min .push (min .peek ());
15
+ }
16
+ }
17
+
18
+ public void pop () {
19
+ st .pop ();
20
+ min .pop ();
21
+ }
22
+
23
+ public int top () {
24
+ return st .peek ();
25
+ }
26
+
27
+ public int getMin () {
28
+ return min .peek ();
29
+ }
30
+
31
+ public static void main (String [] args ) {
32
+ MinStack obj = new MinStack ();
33
+ obj .push (5 );
34
+ System .out .println ("Pushed 5" );
35
+ System .out .println ("Top element: " + obj .top ());
36
+ System .out .println ("Minimum element: " + obj .getMin ());
37
+
38
+ obj .push (3 );
39
+ System .out .println ("Pushed 3" );
40
+ System .out .println ("Top element: " + obj .top ());
41
+ System .out .println ("Minimum element: " + obj .getMin ());
42
+
43
+ obj .push (7 );
44
+ System .out .println ("Pushed 7" );
45
+ System .out .println ("Top element: " + obj .top ());
46
+ System .out .println ("Minimum element: " + obj .getMin ());
47
+
48
+ obj .push (2 );
49
+ System .out .println ("Pushed 2" );
50
+ System .out .println ("Top element: " + obj .top ());
51
+ System .out .println ("Minimum element: " + obj .getMin ());
52
+
53
+ obj .pop ();
54
+ System .out .println ("Popped" );
55
+ System .out .println ("Top element: " + obj .top ());
56
+ System .out .println ("Minimum element: " + obj .getMin ());
57
+ }
58
+ }
You can’t perform that action at this time.
0 commit comments