微软面试100题系列-设计包含 min 函数的栈
2014-02-15 02:44
309 查看
定义栈的数据结构,要求添加一个 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);
}
要求函数 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);
}
相关文章推荐
- (微软面试100题)设计包含min 函数的栈
- 【从零单排之微软面试100题系列】02之包含 min 函数的栈
- 微软面试(2/100)--设计包含函数的栈
- 微软面试100题系列---设计包含min函数的栈
- 【微软100题】002设计包含 min 函数的栈
- 微软面试题系列(二):设计包含 min 函数的栈
- (微软100题)2.设计包含min 函数的栈。
- (微软100题)2.设计包含min 函数的栈。
- 微软面试100题之二 设计包含min函数的栈。
- 面试题系列-----数据结构(设计包含 min 函数的栈(栈))
- 【微软面试100题】2.设计包含min函数的栈
- 【100题】设计包含min 函数的栈
- 每天学习一算法系列(3)--设计包含min函数的栈,要求函数min、push以及pop的时间复杂度都是O(1))
- 每天学习一算法系列(3)(设计包含min函数的栈,要求函数min、push以及pop的时间复杂度都是O(1))
- 微软等面试100题第二题:设计包含min函数的栈
- 微软等面试100题筛选答案-2-设计包含min函数的栈
- [微软面试100题] 设计包含min函数的栈
- 网友答案整理II:微软等面试100题系列之网友精彩回复 [二]
- 2.设计包含min 函数的栈。3.求子数组的最大和
- 微软面试100题系列---把二叉查找树转换成排序的双向链表