-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateMinStack.java
More file actions
57 lines (49 loc) · 1.1 KB
/
CreateMinStack.java
File metadata and controls
57 lines (49 loc) · 1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package stack.question2;
import java.util.Stack;
class MinStack {
Stack<Integer> x;
Stack<Integer> min;
public MinStack() {
x = new Stack<>();
min = new Stack<>();
}
public void push(int val) {
if (min.isEmpty()) {
min.push(val);
min.push(val);
}else{
int top = min.pop();
int currMin = min.peek() < val ? min.peek() : val;
min.push(top);
min.push(currMin);
min.push(val);
}
x.push(val);
}
public void pop() {
x.pop();
min.pop();
min.pop();
}
public int top() {
return x.peek();
}
public int getMin() {
int top = min.pop();
int d = min.peek();
min.push(top);
return d;
}
}
public class CreateMinStack {
public static void main(String[] args) {
MinStack x = new MinStack();
x.push(5);
x.push(8);
x.push(2);
x.push(10);
x.pop();
x.pop();
System.out.println(x.getMin());
}
}