-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack2.java
More file actions
51 lines (45 loc) · 1.05 KB
/
Copy pathMinStack2.java
File metadata and controls
51 lines (45 loc) · 1.05 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
//Time Complexity:
// push: O(1)
// pop: O(1)
// top: O(1)
// getMin: O(1)
//Space Complexity: O(n)
class MinStack2 {
private Node head;
class Node{
int val;
int min;
Node next;
Node(int val, int min, Node next){
this.val = val;
this.min = min;
this.next = next;
}
}
public void push(int x) {
if(head == null){
head = new Node(x, x, null);
}else {
head = new Node(x, Math.min(x, head.min),head);
}
}
public void pop() {
head = head.next;
}
public int top() {
return head.val;
}
public int getMin() {
return head.min;
}
public static void main(String[] args) {
MinStack2 obj = new MinStack2();
obj.push(-2);
obj.push(0);
obj.push(-3);
System.out.println(obj.getMin()); //-3
obj.pop();
System.out.println(obj.top());//0
System.out.println(obj.getMin());//2
}
}