题目:定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push、及pop的时间复杂度都是0(1)。
思路:建立一个数据栈和辅助栈,数据栈是正常压入数据,辅助栈是压入最小数据的。比如现在要往栈里添加的元素为:4,3,6,2入栈动作如下:
1.因为4是第一个元素,所以它同时压入数据栈和辅助栈。
2.然后是3,因为3比4小,所以也同时压入数据栈和辅助栈。
3.接下去是6,因为6比辅助栈中的最小元素3大,所以它不压入辅助栈,但需往辅助栈再压入一个3,这样确保在数据栈3未被弹出之前最小值保持3.
4.因为2比3小,所以也同时压入数据栈和辅助栈。
测试用例:正常测试。
#include<iostream>
#include<stack>
#include<cstdio>
using namespace std;
template<typename T> class StackWithMin
{
public:
StackWithMin(){}
virtual ~StackWithMin(){}
void push(const T& value);
void pop();
const T& min() const;
private:
stack<T> m_data;
stack<T> m_min;
};
template <typename T> void StackWithMin<T>::push(const T& value)
{
m_data.push(value);
if (m_min.size() == 0 || value < m_min.top())
{
m_min.push(value);
}
else
{
m_min.push(m_min.top());
}
}
template <typename T> void StackWithMin<T>::pop()
{
if (m_data.size() > 0 && m_min.size() > 0)
{
m_data.pop();
m_min.pop();
}
}
template <typename T> const T& StackWithMin<T>::min() const
{
if (m_data.size() > 0 && m_min.size() > 0)
{
return m_min.top();
}
}
void Test(const StackWithMin<int>& stack, int expected)
{
if (stack.min() == expected)
{
cout << "pass!" << endl;
}
else
{
cout << "failed!" << endl;
}
}
int main()
{
StackWithMin<int> stack;
stack.push(3);
Test(stack, 3);
stack.push(4);
Test(stack, 3);
stack.push(2);
Test(stack, 2);
stack.push(3);
Test(stack, 2);
stack.pop();
Test(stack, 2);
stack.pop();
Test(stack, 3);
stack.pop();
Test(stack, 3);
stack.push(0);
Test(stack, 0);
return 0;
}