Skip to content

Commit 8054e5c

Browse files
author
applewjg
committed
Min Stack
Change-Id: I9e549f77593c9dc1690a2620a8de952d3e287cad
1 parent a9d24c0 commit 8054e5c

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

MinStack.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Nov 14, 2014
4+
Problem: Min Stack
5+
Difficulty: Easy
6+
Source: https://oj.leetcode.com/problems/min-stack/
7+
Notes:
8+
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
9+
push(x) -- Push element x onto stack.
10+
pop() -- Removes the element on top of the stack.
11+
top() -- Get the top element.
12+
getMin() -- Retrieve the minimum element in the stack.
13+
*/
14+
15+
class MinStack {
16+
private Stack<Integer> stack = new Stack<>();
17+
private Stack<Integer> minStack = new Stack<>();
18+
public void push(int x) {
19+
stack.push(x);
20+
if (minStack.isEmpty() || x <= minStack.peek()) {
21+
minStack.push(x);
22+
}
23+
}
24+
public void pop() {
25+
if (stack.pop().equals(minStack.peek())) minStack.pop();
26+
}
27+
public int top() {
28+
return stack.peek();
29+
}
30+
public int getMin() {
31+
return minStack.peek();
32+
}
33+
}

0 commit comments

Comments
 (0)