最小栈
#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();
int x;
printf("input the number of x untill -1\n");
while(1)
{
scanf("%d",&x);
if(x==-1)
break;
push(s_data,x);
if( Empty(s_min) || x<=top(s_min) )
{
push(s_min,x);
}
}
int min=GetMin(s_min);
printf("min=%d",min);
free(s_data);
free(s_min);
}