/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: main.cpp
* Author: Administrator
*
* Created on 2017年5月2日, 下午10:52
*/
#include <cstdlib>
#include <stack>
#include <vector>
#include <iostream>
using namespace std;
/*
*
*/
template <typename T>
class min_stack
{
struct dataType
{
T data;
unsigned index;//用于记录最小元素的下标
dataType():data(),index(0xFFFFFFFF){}
dataType(T d, unsigned i):data(d),index(i){}
};
private:
vector<dataType> _m_stack;
unsigned _min;//记录当前栈顶最小元素的索引
public:
min_stack():_m_stack(),_min(0xFFFFFFFF) {}
~min_stack();
void push(T data);
void pop();
T min();
};
template <typename T>
min_stack<T>::~min_stack()
{}
template <typename T>
void min_stack<T>::push(T data)
{
_m_stack.push_back(dataType(data, _min));
if (0xFFFFFFFF == _min)
{
_min = 0;
return;
}
if (data < _m_stack[_min].data)
{
_min = _m_stack.size() - 1;
return;
}
}
template <typename T>
void min_stack<T>::pop()
{
if (0 == _m_stack.size()) return;
_min = (_m_stack.back()).index;
_m_stack.pop_back();
}
template <typename T>
T min_stack<T>::min()
{
return _m_stack[_min].data;
}
int main(int argc, char** argv) {
int min;
min_stack<int> test;
test.push(4);
test.push(5);
test.push(7);
test.push(2);
min = test.min();
cout << min << endl;
test.push(1);
min = test.min();
cout << min << endl;
test.pop();
min = test.min();
cout << min << endl;
test.pop();
min = test.min();
cout << min << endl;
test.pop();
min = test.min();
cout << min << endl;
test.pop();
min = test.min();
cout << min << endl;
system("pause");
return 0;
}