标签:
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Stack Data Structure
#include <iostream> #include <stack> using namespace std; class MinStack { public: stack<int> data; stack<int> support; void push(int x) { if(data.empty()){ data.push(x); support.push(x); } else{ data.push(x); if(x<=support.top()) support.push(x); } } void pop() { if(data.top()==support.top()) support.pop(); data.pop(); } int top() { return data.top(); } int getMin() { return support.top(); } }; int main() { MinStack myMinStack; myMinStack.push(1); cout<<myMinStack.getMin()<<endl; myMinStack.push(2); cout<<myMinStack.getMin()<<endl; myMinStack.push(0); cout<<myMinStack.getMin()<<endl; myMinStack.pop(); myMinStack.pop(); cout<<myMinStack.getMin()<<endl; myMinStack.pop(); return 0; }
标签:
原文地址:http://www.cnblogs.com/Azhu/p/4324442.html