定义栈的数据结构,要求添加一个 min 函数,能够得到栈的最小元素。
要求函数 min、push 以及 pop 的时间复杂度都是 O(1)。
#define STACK_SZ 10
struct stack{
int buf[STACK_SZ];
int top_index;
int min_index;
};
int is_empty(struct stack * s)
{
return s->top_index == -1;
}
int is_full(struct stack * s)
{
return s->top_index == STACK_SZ - 1;
}
int push(struct stack * s, int elem)
{
if(is_full(s))
return 0;
s->top_index++;
s->buf[s->top_index] = elem;
if(s->min_index == -1)
s->min_index = s->top_index;
else if(s->buf[s->min_index] > elem)
s->min_index = s->top_index;
return 1;
}
int pop(struct stack * s, int * elem)
{
if(is_empty(s))
return 0;
*elem = s->buf[s->top_index];
s->top_index--;
return 1;
}
void init_stack(struct stack * s)
{
s->top_index = s->min_index = -1;
}
int get_min(struct stack * s, int * elem)
{
if(s->min_index == -1)
return 0;
*elem = s->buf[s->min_index];
return 1;
}
int main(int c, char * v[])
{
struct stack s;
int min;
init_stack(&s);
if(get_min(&s, &min))
printf("min value is : %d\n", min);
push(&s, 4);
push(&s, 3);
push(&s, 4);
push(&s, 4);
if(get_min(&s, &min))
printf("min value is : %d\n", min);
}