设计包含min或max功能的栈

问题: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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值