您的位置:首页 > 职场人生

剑指Offer----面试题21:包含min函数的栈

2016-06-04 23:39 716 查看

题目:

定义栈的数据结构,请在该类型中实现一个能够得到栈的最小元素的min函数。在该栈中,调用min、push及pop的时间复杂度都是O(1)。

分析:

使用两个栈,一个数据栈,一个辅助栈,数据栈中存放数据,辅助栈中依次存放较小的值。





源代码:

头文件StackWithMin.h
#ifndef STACKWITHMIN_H
#define STACKWITHMIN_H

#include<stack>

namespace StackWithMinSpace
{
class ThrowError{};

template<typename T>
class StackWithMin
{
public:
StackWithMin(void){}
virtual ~StackWithMin(){}

T &top();
const T &top() const;

void pop();
void push(T const &t);
const T &min() const;

bool empty();
int size();

private:
std::stack<T> dataStk;
std::stack<T> minStk;
};

}
#endif


实现文件StackWIthMin.cpp
#include"StackWithMin.h"

namespace StackWithMinSpace
{
template<typename T>
bool StackWithMin<T>::empty()
{
return dataStk.empty();
}

template<typename T>
int StackWithMin<T>::size()
{
return dataStk.size();
}

template<typename T>
void StackWithMin<T>::push(T const &t)
{
dataStk.push(t);

if (minStk.empty() || t < minStk.top())
minStk.push(t);
else
minStk.push(minStk.top());
}

template<typename T>
void StackWithMin<T>::pop()
{
if (dataStk.empty())
{
throw ThrowError{};
}

dataStk.pop();
minStk.pop();
}

//const T &min() const;
template<typename T>
const T & StackWithMin<T>::min() const
{
if (minStk.empty())
{
throw ThrowError{};
}

return minStk.top();
}

template<typename T>
T &StackWithMin<T>::top()
{
if (dataStk.empty())
{
throw ThrowError{};
}

return dataStk.top();
}

template<typename T>
const T &StackWithMin<T>::top() const
{
if (dataStk.empty())
{
throw ThrowError{};
}

return dataStk.top();
}
}


测试文件:
//#include"StackWithMin.h"
#include"StackWithMin.cpp"
#include<iostream>

using std::cout;
using std::endl;

using namespace StackWithMinSpace;

void test11()
{
StackWithMin<int> stk;
stk.push(5);
stk.push(4);
stk.push(2);
stk.push(2);
stk.push(1);

cout << "栈的大小" << stk.size() << endl;
cout << "最小的数字为:" << stk.min() << endl;

stk.pop();

cout << "栈的大小" << stk.size() << endl;
cout << "最小的数字为:" << stk.min() << endl;

stk.pop();

cout << "栈的大小" << stk.size() << endl;
cout << "最小的数字为:" << stk.min() << endl;

stk.pop();

cout << "栈的大小" << stk.size() << endl;
cout << "最小的数字为:" << stk.min() << endl;
}

int main()
{
test11();
cout << endl;

system("pause");
return 0;
}


运行结果:

栈的大小5
最小的数字为:1
栈的大小4
最小的数字为:2
栈的大小3
最小的数字为:2
栈的大小2
最小的数字为:4

请按任意键继续. . .


另外转载一篇<模板类的定义和声明为什么要写在一起>的文章,欢迎阅读!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 剑指offer 面试题