-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path155-minStack.java
62 lines (52 loc) · 1.24 KB
/
155-minStack.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
56
57
58
59
60
61
62
class MinStack {
static class Node {
int val; // value element
Node next; // next
}
Node top;
public MinStack() {
top = null; // initialise the top as null
}
public void push(int val) {
Node newNode = new Node();
if (newNode == null){
System.out.println("Stack Overflow");
}
else{
newNode.val = val;
newNode.next = top;
top = newNode;
}
}
public void pop() {
if (top == null){
System.out.println("Stack Underflow");
}
else{
top = top.next;
}
}
public int top() {
if (top == null){
System.out.println("Stack is empty");
}
return top.val;
}
public int getMin() {
int min = Integer.MAX_VALUE;
Node temp = top;
while (temp != null){
if (temp.val < min) min=temp.val;
temp = temp.next;
}
return min;
}
}
/**
* Your MinStack object will be instantiated and called as such:
* MinStack obj = new MinStack();
* obj.push(val);
* obj.pop();
* int param_3 = obj.top();
* int param_4 = obj.getMin();
*/