-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetMinStack.java
More file actions
37 lines (30 loc) · 810 Bytes
/
GetMinStack.java
File metadata and controls
37 lines (30 loc) · 810 Bytes
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
package gfg.ds.stack;
import java.util.ArrayDeque;
public class GetMinStack {
private ArrayDeque<Integer> stack = new ArrayDeque<>();
private ArrayDeque<Integer> minStack = new ArrayDeque<>();
/**
* we have to push for equals to only for multiple entries of minimum element.
*/
public void push(int data) {
this.stack.push(data);
if (minStack.isEmpty() || minStack.peek() >= data) {
minStack.push(data);
}
}
public int pop() {
assert !isEmpty() : "Stack is empty";
assert stack.peek() != null;
if (stack.peek().equals(minStack.peek())) {
minStack.pop();
}
return stack.pop();
}
public int getMin() {
assert !isEmpty() : "Stack is empty";
return minStack.peek();
}
public boolean isEmpty() {
return stack.isEmpty();
}
}