leetcode Min Stack

题目连接

https://leetcode.com/problems/min-stack/  

Min Stack

Description

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.

class MinStack {
public:
	void push(int x) {
		if (val.empty() || x <= val.top()) val.push(x);
		num.push(x);
	}
	void pop() {
		if (num.top() <= val.top()) val.pop();
		num.pop();
	}
	int top() {
		return num.top();
	}
	int getMin() {
		return val.top();
	}
private:
	stack<int> num;
	stack<int> val;
};
posted @ 2015-12-09 20:02  GadyPu  阅读(135)  评论(0编辑  收藏  举报