添加一个min()函数求栈的最小元素,要求复杂度在O(1)。
通过双栈方法实现。同时建一个minstack栈,记录最小值元素与栈顶值之间的差。
如果minstack栈顶值为i小于0,说明stack栈最小值与栈顶相差i个位置;
如果minstack栈顶值不小于即为0,说明stack栈最小值为栈顶值;
/*----------栈中min值问题,复杂度O(1)----------*/
#include <iostream>
#include "stack.hpp"
class minsolu
{
public:
Stack<int> *stack = new Stack<int>();
Stack<int> *minstack = new Stack<int>();
//入栈
bool Push(int data)
{
if (stack->top > stack->maxSize)//防溢出
return false;
if (stack->top == -1)//空栈压入
{
stack->Push(data);
minstack->Push(0);
return true;
}
if (data < stack->elements[stack->top + minstack->elements[minstack->top]])
{ //如果入栈值小于当前最小值
stack->Push(data);
minstack->Push(0);
return true;
}
else
{ //如果入栈值大于当前最小值
stack->Push(data);
minstack->Push(minstack->elements[minstack->top] - 1);
return true;
}
}
//出栈
int Pop()
{
if (stack->top == -1)
{
exit(1);
}
minstack->Pop();
return stack->Pop();
}
//求最小值
int min()
{
if (stack->top == -1)
{
exit(1);
}
//最小值为stack栈top值加minstack栈中top值元素;
return stack->elements[stack->top + minstack->elements[minstack->top]];
}
bool isEmpty()
{
if (stack->top != -1)
return false;
else
return true;
}
};
int main()
{
minsolu *test01 = new minsolu();
int b[] = {
6,
8,
15,
2,
3,
1,
2,
};
cout << "入栈情况:" << endl;
for (int i = 0; i < 7; i++)
{
test01->Push(b[i]);
cout << "入栈值" << b[i] <<"\t\t";
cout << "当前最小值" << test01->min() << endl;
}
cout << "出栈情况:" << endl;
while (!test01->isEmpty())
{
cout << "出栈值" << test01->Pop() << "\t\t";
cout << "当前最小值" << test01->min() << endl;
}
system("pause");
return 0;
}
运行情况如下: