Skip to content

Commit d8c124b

Browse files
authored
Merge pull request #1088 from Rahul8691/Rahul8691-patch-2
Added Solution for LeetCode Problem No. 155
2 parents 7eddd47 + 9829e6c commit d8c124b

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

LeetCode/155. Min Stack/Solution.java

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class MinStack {
2+
int min = Integer.MAX_VALUE;
3+
Stack<Integer> stack = new Stack<Integer>();
4+
public void push(int x) {
5+
// only push the old minimum value when the current
6+
// minimum value changes after pushing the new value x
7+
if(x <= min){
8+
stack.push(min);
9+
min=x;
10+
}
11+
stack.push(x);
12+
}
13+
14+
public void pop() {
15+
// if pop operation could result in the changing of the current minimum value,
16+
// pop twice and change the current minimum value to the last minimum value.
17+
if(stack.pop() == min) min=stack.pop();
18+
}
19+
20+
public int top() {
21+
return stack.peek();
22+
}
23+
24+
public int getMin() {
25+
return min;
26+
}
27+
}

0 commit comments

Comments
 (0)