Skip to content

Commit 38d8515

Browse files
author
applewjg
committed
MinStack.h
1 parent 96c5699 commit 38d8515

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed

MinStack.h

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
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+
public:
17+
void push(int x) {
18+
elements.push(x);
19+
if (minstk.empty() || x <= minstk.top()) {
20+
minstk.push(x);
21+
}
22+
}
23+
24+
void pop() {
25+
if (elements.empty()) {
26+
return;
27+
}
28+
if (elements.top() == minstk.top()) {
29+
minstk.pop();
30+
}
31+
elements.pop();
32+
}
33+
34+
int top() {
35+
return elements.top();
36+
}
37+
38+
int getMin() {
39+
return minstk.top();
40+
}
41+
private:
42+
stack<int> elements;
43+
stack<int> minstk;
44+
};

0 commit comments

Comments
 (0)