您的位置:首页 > 其它

LeetCode 155. Min Stack

2016-04-19 11:58 246 查看
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.

push(x) -- Push element x onto stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
getMin() -- Retrieve the minimum element in the stack.

Perhaps, this is the most lazy way.....I will update other methods later.

#include <iostream>
#include <stack>
using namespace std;

class MinStack{
private:
struct value {
int data;
int currMin;
};
stack<value> nodes;
public:
void push(int  x) {
if(nodes.empty()) {
nodes.push({x, x});
} else {
value tmp;
tmp.data = x;
tmp.currMin = min(x, nodes.top().currMin);
nodes.push(tmp);
}
}

void pop() {
nodes.pop();
}

int top() {
return nodes.top().data;
}

int getMin() {
return nodes.top().currMin;
}
};

int main(void) {
MinStack myStack;
myStack.push(1);
myStack.push(2);
cout << myStack.getMin() << endl;
myStack.push(0);
cout << myStack.getMin() << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: