问题:对Stack(栈)数据结构进行改进,加一个min()或max()功能,使之能在常数,即O(1),时间内给出栈中的最小值。可对push()和pop()函数进行修改,但要求其时间复杂度都只能是O(1)。
以下只对如何求min进行阐述,max类似处理。
解题思路:
用min数组记录当前最小值。当有新数值x进栈时,就前一次的最小值进行比较,如果小于就将min值进行替换,否则保留。、
详见代码:
#include<iostream>
#define MAX 5
using namespace std;
struct stack
{
int data[MAX];
int top;
int min[MAX];
};
void init(stack* s)//初始化
{
s->top=0;
}
int push(stack* s,int x)
{
if(s->top==MAX)
{
cout<<"Stack is full!"<<endl;
return -1;
}
if(s->top==0)
{
s->data[s->top]=x;
s->min[s->top]=x;
s->top++;
}
else
{
s->data[s->top]=x;
if(x<s->min[s->top -1])//比min小就替换
{
s->min[s->top]=x;
}
else//否则和上一个最小值一样
{
s->min[s->top]=s->min[s->top-1];
}
s->top++;
}
return 0;
}
int pop(stack* s)
{
if(s->top<0)
{
cout<<"Null!"<<endl;
return -1;
}
int x;
x=s->data[s->top--];
return x;
}
int minValue(stack* s,int x)
{
x=s->min[s->top];
return x;
}
int main()
{
int i;
int x;
stack* a=new stack;
init(a);
cout<<"Please input five numbers."<<endl;
for (i=1; i<=MAX; i++)
{
cin>>x;
push(a,x);
cout<<"第"<<i<<"个数="<<x<<", min = "<<a->min[a->top-1]<<endl;
}
a->top--;
cout<<"当前栈的最小值:"<<a->min[a->top]<<endl;
for(int k = 0; k< 5; k++) // 测试,说明入栈之后data里面确实是输入的5个数,而且后输入的在栈的上部
cout<<a->data[k]<<' ';
cout<<endl;
for (i=1; i<=MAX; i++)
{
cout<<pop(a)<<" ";
cout<<"出栈后,栈的最小值:"<<a->min[a->top]<<endl;
}
return 0;
}