forked from super30admin/Design-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
64 lines (51 loc) · 1.28 KB
/
Copy pathMinStack.java
File metadata and controls
64 lines (51 loc) · 1.28 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
58
59
60
61
62
63
64
// Time Complexity : O(1)
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
import java.util.*;
public class MinStack {
Stack<Integer> stack;
int min;
public MinStack() {
this.stack = new Stack<Integer>();
//this.min = Integer.MAX_VALUE;
}
public void push(int val) {
if(stack.isEmpty())
{
stack.push(val); //pushing the previous minimum value
stack.push(val); ////pushing the value
min = val;
return;
}
if(val <= min)
{
stack.push(min); // pushing the minimum to be stored as previous minimum
min = val; //storing the current value as minimum value
}
stack.push(val); //pushing the current value
}
public void pop() {
if(!stack.isEmpty())
{
int popValue = stack.pop();
if(popValue == min)
{
min = stack.pop();
}
}
}
public int top() {
return stack.peek();
}
public int getMin() {
return min;
}
public static void main(String args[])
{
MinStack minStack = new MinStack();
minStack.push(3);
minStack.push(-2);
minStack.pop();
minStack.pop();
}
}