File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ package Chap4 ;
2+
3+ import java .util .LinkedList ;
4+
5+ public class MinStack {
6+
7+ private LinkedList <Integer > stack ;
8+ private LinkedList <Integer > minStack ;
9+
10+ /** initialize your data structure here. */
11+ public MinStack () {
12+ stack =new LinkedList <>();
13+ minStack = new LinkedList <>();
14+ }
15+
16+ public void push (int x ) {
17+ stack .push (x );
18+ if (minStack .isEmpty () || x <= minStack .peek ()) {
19+ minStack .push (x );
20+ }
21+ }
22+
23+ public void pop () {
24+ if (stack .isEmpty ()) {
25+ return ;
26+ }
27+ if (stack .pop ().equals (minStack .peek ())) {
28+ minStack .pop ();
29+ }
30+ }
31+
32+ public int top () {
33+ if (stack .isEmpty ()) {
34+ return -1 ;
35+ }
36+ return stack .peek ();
37+ }
38+
39+ public int min () {
40+ if (minStack .isEmpty ()) {
41+ return -1 ;
42+ }
43+ return minStack .peek ();
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments