最小栈

最小栈

#include<stdio.h>
#include<stdlib.h>
#define MAX 30

typedef int elemtype;
typedef struct {
	elemtype a[30];
	int top;
}Stack;


Stack* InitStack()
{
	Stack *s=(Stack *)malloc(sizeof(Stack));
	s->top=0;
	return s;
}


int Empty(Stack *s)
{
	if(s->top==0)
		return 1;
	else
		return 0;	
}


int push(Stack *s,elemtype x)
{
	if(s->top==MAX)
		return 0;
	else{
		s->a[s->top++]=x;
		return 1;
	}
}


int pop(Stack *s,elemtype *x)
{
	if(Empty(s))
		return 0;
	else{
		*x=s->a[--s->top];
		return 1;
	}	
}


int top(Stack *s)
{
	if(Empty(s))
		return 0;
	else
		return s->a[s->top-1];
}


int GetMin(Stack *s)
{
	if(Empty(s))
	{
		printf("the stack is empty\n");
		return 0;
	}
	else
	return s->a[s->top-1];
}


void print(Stack *s)
{
	int i;
	for ( i=0;i<s->top;i++)
	{
		printf("%d--",s->a[i]);
	}
	printf("\n");
}


int main()
{
	Stack *s_data=InitStack();
	//辅助栈,确定最小 
	Stack *s_min=InitStack();
	// 以空间换时间,让时间复杂度为O(1) 
	int x;
	printf("input the number of x untill -1\n");
	while(1)
	{
		scanf("%d",&x);
		if(x==-1)
			break;
		push(s_data,x);
		//x=最小值的也要,为了pop数据栈时可以同步 
		if( Empty(s_min) || x<=top(s_min) )
		{
			push(s_min,x);
		}
	}

//	pop(s_data,&x);
//	if(x==top(s_min))
//		pop(s_min,&x);
	
	int min=GetMin(s_min);
	printf("min=%d",min);
	
	free(s_data);
	free(s_min);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值