File tree Expand file tree Collapse file tree 1 file changed +14
-19
lines changed Expand file tree Collapse file tree 1 file changed +14
-19
lines changed Original file line number Diff line number Diff line change 1
1
class MaxStack {
2
- private Stack <Integer > stack , maxStack ;
2
+ private Stack <Integer > st , maxSt ;
3
3
4
4
public MaxStack () {
5
- stack = new Stack <>();
6
- maxStack = new Stack <>();
5
+ st = new Stack <>();
6
+ maxSt = new Stack <>();
7
7
}
8
8
9
9
public void push (int x ) {
10
- int tempMax = maxStack .isEmpty () ? Integer .MIN_VALUE : maxStack .peek ();
10
+ int max = maxSt .isEmpty () ? Integer .MIN_VALUE : maxSt .peek ();
11
+ max = Math .max (max , x );
11
12
12
- if (x > tempMax ) {
13
- tempMax = x ;
14
- }
15
-
16
- maxStack .push (tempMax );
17
- stack .push (x );
13
+ st .push (x );
14
+ maxSt .push (max );
18
15
}
19
16
20
17
public int pop () {
21
- maxStack .pop ();
22
- return stack .pop ();
18
+ maxSt .pop ();
19
+ return st .pop ();
23
20
}
24
21
25
22
public int top () {
26
- return stack .peek ();
23
+ return st .peek ();
27
24
}
28
25
29
26
public int peekMax () {
30
- return maxStack .peek ();
27
+ return maxSt .peek ();
31
28
}
32
29
33
30
public int popMax () {
34
31
int max = peekMax ();
35
32
36
33
Stack <Integer > buffer = new Stack <>();
37
34
38
- while (stack .peek () != max ) {
39
- buffer .push (stack .pop ());
40
- maxStack .pop ();
35
+ while (top () != max ) {
36
+ buffer .push (pop ());
41
37
}
42
-
43
38
pop ();
44
-
45
39
while (!buffer .isEmpty ()) {
46
40
push (buffer .pop ());
47
41
}
42
+
48
43
return max ;
49
44
}
50
45
}
You can’t perform that action at this time.
0 commit comments