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

面试题-Stack的最小值o(1)

2016-01-31 11:16 489 查看
// Stack.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

template <class Type>
struct Stack
{
private:
Type *_stack;
int _top;
int _min;
int _size;

public:
Stack(const Type &size):_size(size),_top(0),_min(0)
{
_stack = new Type[size];//(Type*)malloc(sizeof())
}
void push(const Type &value)
{

if(_top == 0)
{
_min = value;
}
else if(_top == _size)
{
cout<<"Push failed,the stack is full"<<endl;
return;
}
_stack[_top++] = value-_min;
if(value < _min)
{
_min = value;
}

}
Type pop()
{
if(_top == 0)
{
cout<<"Pop failed,the stack is emply."<<endl;
return -1;
}
Type popvalue;
if(_stack[--_top]<0)
{
popvalue = _min;
_min = _min-_stack[_top];
}
else
{
popvalue = _min + _stack[_top];
}
return popvalue;
}
Type min()
{
return _min;
}

};

int _tmain(int argc, _TCHAR* argv[])
{
Stack<int> sk(30);
sk.push(8);
sk.push(7);
sk.push(6);
sk.push(5);
sk.push(9);
sk.push(4);
sk.push(3);

cout<<sk.min()<<endl;//3
cout<<sk.pop()<<endl;//3
cout<<sk.min()<<endl;//4
cout<<sk.pop()<<endl;//4
cout<<sk.min()<<endl;//5
cout<<sk.pop()<<endl;//9
cout<<sk.min()<<endl;//5
cout<<sk.pop()<<endl;//5
cout<<sk.min()<<endl;//6
cout<<sk.pop()<<endl;//6
cout<<sk.min()<<endl;//7
cout<<sk.pop()<<endl;//7
cout<<sk.min()<<endl;//8
cout<<sk.pop()<<endl;//8

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: