定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都
是O(1)。 分析:这是去年google的一道面试题。
//============================================================================
// Name : StackGog.cpp
// Author : Lee
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include <stack>
#include <deque>
using namespace std;
template <typename T> class StackMin{
private:
stack<T> data_stack;//store data
stack<T> min_stack;//store minimum data
public:
StackMin();
StackMin(deque<T> deq,deque<T> min):data_stack(deq),min_stack(min){}
virtual ~ StackMin(){};
void push(T);
void pop();
T top();
//const T& top()const;
T min();
};
template <typename T> void StackMin<T>::push(T data){
data_stack.push(data);
if(data_stack.size()==1){
min_stack.push(data);
}else{
//if the data to be stored is smaller than the
//minum data,then push it in to minimun stack,
//else push the top of minumun again to minimun stack
T min=min_stack.top();
if(data<min){
min_stack.push(data);
}else{
min_stack.push(min);
}
}
}
template <typename T> void StackMin<T>::pop(){
data_stack.pop();
min_stack.pop();
}
template <typename T> T StackMin<T>::top(){
return data_stack.top();
}
template <typename T> T StackMin<T>::min(){
return min_stack.top();
}
int main() {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
int a[5]={3,4,2,6,1};
deque<int> deq;
deque<int> min;
StackMin<int> int_stack(deq,min);
for(int i=0;i<5;i++){
int_stack.push(a[i]);
cout<<int_stack.min()<<endl;
}
return 0;
}