File tree Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Expand file tree Collapse file tree 1 file changed +85
-0
lines changed Original file line number Diff line number Diff line change 1+ package revision ;
2+
3+ import java .util .Stack ;
4+
5+ public class FindMaxinStack {
6+
7+ Stack <Integer > stk = new Stack <>();
8+ int max ;
9+
10+ public void getMax () {
11+
12+ if (stk .empty ()) {
13+ System .out .println ("no element" );
14+ } else {
15+ System .out .println (max );
16+ }
17+ }
18+
19+ public void peek () {
20+
21+ if (stk .empty ()) {
22+ System .out .println ("stack is empty" );
23+ }
24+
25+ int top = stk .peek ();
26+
27+ if (top > max ) { // here it means max contains the top element.
28+ System .out .println (max );
29+ } else {
30+ System .out .println (top );
31+ }
32+
33+ }
34+
35+
36+ public void pop () {
37+
38+ if (stk .isEmpty ()) {
39+ System .out .println ("empty" );
40+ return ;
41+ }
42+
43+ int top = stk .peek ();
44+ stk .pop ();
45+ if (top > max ) {
46+ System .out .println (max );
47+ max = 2 * max - top ;
48+ } else {
49+ System .out .println (top );
50+ }
51+
52+ }
53+
54+
55+ public void push (int elem ) {
56+
57+ if (stk .isEmpty ()) {
58+
59+ max = elem ;
60+ stk .push (elem );
61+ return ;
62+ }
63+
64+ if (elem > max ) {
65+ stk .push (2 * elem - max );
66+ max = elem ;
67+ } else {
68+ stk .push (elem );
69+ }
70+
71+
72+ }
73+
74+
75+ public static void main (String [] args ) {
76+
77+ FindMaxinStack obj = new FindMaxinStack ();
78+ obj .push (3 );
79+ obj .pop ();
80+ obj .getMax ();
81+ }
82+
83+
84+
85+ }
You can’t perform that action at this time.
0 commit comments