C++使用两个栈实现一个可以获取栈中最大值和最小值的栈

来源:互联网 发布:php tp框架分页源代码 编辑:程序博客网 时间:2024/06/16 15:18
#include <iostream>
#include <stack>


struct stack_pro {
std::stack<int> stk_data;
std::stack<int> stk_min;
};


void push(stack_pro &stk, const int &num);
void pop(stack_pro &stk, int & tag);
void getmin(stack_pro &stk, int &getmin_tag, int &min);


int main()
{
stack_pro stk;
int tag = 0;
int getmin_tag = 0;
int min;
int arr[8] = { 3, 5, 6, 7, 1 };


for (int i = 0; i < 5; ++i)
{
push(stk, arr[i]);
getmin(stk, getmin_tag, min);
if (getmin_tag == 0)
{
std::cout << min << std::endl;
}

}


std::cout << std::endl;


for (int i = 0; i < 5; ++i)
{
getmin(stk, getmin_tag, min);
if (getmin_tag == 0)
{
std::cout << min << std::endl;
}
pop(stk, tag);
}






system("pause");
return 0;
}


void push(stack_pro &stk, const int &num)
{
if (stk.stk_data.empty())
{
stk.stk_data.push(num);
stk.stk_min.push(num);
}
else
{
stk.stk_data.push(num);
if (num <= stk.stk_min.top())
{
stk.stk_min.push(num);
}
}
}


void pop(stack_pro &stk, int & tag)
{
if (stk.stk_data.empty())
{
tag = -1; //tag = -1,无法弹出栈顶元素
}
else if (stk.stk_data.top() == stk.stk_min.top())
{
stk.stk_data.pop();
stk.stk_min.pop();
}
else
stk.stk_data.pop();
}


void getmin(stack_pro &stk, int &getmin_tag,int &min)
{
if (stk.stk_data.empty())
{
getmin_tag = -1;
}
else
{
getmin_tag = 0;
min = stk.stk_min.top();
}

}
原创粉丝点击