您的位置:首页 > 运维架构

1. 实现一个栈,要求实现 Push (出栈)、 Pop (入栈)、 Min (返回最小值的操作) 的时间复杂度为 O(1)

2017-05-26 20:33 513 查看


class achievestack
{
public:
void push(int value)
{
if (s1.empty() && s2.empty())
{
s1.push(value);
s2.push(value);
}
else
{
if (value <= s2.top())
{
s2.push(value);
}
s1.push(value);
}
}
void pop()
{
if (s2.top() == s1.top())
{
s2.pop();
}
s1.pop();
}
int min()
{
return s2.top();
}
protected:
stack<int> s1;
stack<int> s2;
};
int main()
{
achievestack s;
s.push(3);
s.push(4);
s.push(5);
s.push(16);
s.push(1);
s.push(1);
s.push(2);
cout << s.min() << endl;
s.pop();
s.pop();
cout << s.min() << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐