-
Notifications
You must be signed in to change notification settings - Fork 0
/
P94.java
55 lines (44 loc) · 1.19 KB
/
P94.java
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
import java.util.*;
import java.io.*;
class node {
int val;
int min;
node(int val, int min) {
this.val = val;
this.min = min;
}
}
public class P94 {
static class MinStack {
Stack<node> stk = new Stack<>();
MinStack() {
}
// Function to add another element equal to num at the top of stack.
void push(int num) {
if (stk.isEmpty())
stk.push(new node(num, num));
else
stk.push(new node(num, Math.min(stk.peek().min, num)));
}
// Function to remove the top element of the stack.
int pop() {
if (stk.isEmpty())
return -1;
return stk.pop().val;
}
// Function to return the top element of stack if it is present. Otherwise
// return -1.
int top() {
if (stk.isEmpty())
return -1;
return stk.peek().val;
}
// Function to return minimum element of stack if it is present. Otherwise
// return -1.
int getMin() {
if (stk.isEmpty())
return -1;
return stk.peek().min;
}
}
}