您的位置:首页 > 职场人生

【剑指offer】面试题21:包含min函数的栈

2014-06-16 23:24 423 查看
题目描述:

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。在该栈中,调用min,push和pop时间复杂度都是O(1)

题目解析:

要得到栈的最小值,我们可以通过一个变量,来保存整个入栈过程中的最小值。但是问题来了,如果将最小数据出栈了以后,剩下的最小值如何来保存?

一种很直接的方法,我可以另外设一个“序列”,里面的元素排序,入栈的同时,也把当前节点插入到这个序列当中。不过由于要插入,这样复杂度就不是O(1)了。换个角度考虑,我们每次在这个序列当中,每次放入节点的同时,也把当前整个栈中的最小值放入序列中,比如3,3,2,2,1……这样当我们出栈时,将最小值退出栈,响应的序列最小值也会变化。

完整代码如下:

#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

#define STACKINIT 50
#define STACKINCREMENT 10

typedef struct StackNode{
int *base;
int *top;
int stacksize;
}StackNode;

int PopMin(StackNode SMin,int *e);
void InitStack(StackNode *S);
void Push(StackNode *S,StackNode *SMin,int e);
int PopStack(StackNode *S,StackNode *SMin,int *e);

int main(void)
{
int n,flag;
char ch;
StackNode st,smin;

InitStack(&st);
InitStack(&smin);
while(scanf("%c",&ch) == 1){
switch(ch){
case 'a':
printf("push:");
scanf("%d",&n);
Push(&st,&smin,n);
break;
case 'b':
flag = PopStack(&st,&smin,&n);
if(flag)
printf("popstack:%d\n",n);
else
printf("the stack is empty!\n");
break;
case 'c':
flag = PopMin(smin,&n);
if(flag)
printf("popmin:%d\n",n);
else
printf("the stack is empty!\n");
break;
default:
printf("please input a/b/c\n");
}
while(getchar() != '\n')
;
}

return 0;
}

void InitStack(StackNode *S)
{
S->base = (int *)malloc(STACKINIT * sizeof(int));
if(!(S->base))
exit(-1);
S->top = S->base;
S->stacksize = STACKINIT;
}

void Push(StackNode *S,StackNode *SMin,int e)
{
if(S->top - S->base >= S->stacksize){
S->base = (int *)realloc(S->base,(S->stacksize + STACKINCREMENT) * sizeof(int));
if(!(S->base))
exit(-1);
S->top = S->base + S->stacksize;
S->stacksize += STACKINCREMENT;
}
*(S->top) = e;
++S->top;

if(SMin->top - SMin->base >= SMin->stacksize){
SMin->base = (int *)realloc(SMin->base,(SMin->stacksize + STACKINCREMENT) * sizeof(int));
if(!(SMin->base))
exit(-1);
SMin->top = SMin->base + SMin->stacksize;
SMin->stacksize += STACKINCREMENT;
}
if(*(SMin->top-1) > e)
*(SMin->top) = e;
else
*(SMin->top) = *(SMin->top - 1);
SMin->top++;
}

int PopStack(StackNode *S,StackNode *SMin,int *e)
{
if(S->top == S->base)
return FALSE;
*e = *(--S->top);
--SMin->top;
return TRUE;
}

int PopMin(StackNode SMin,int *e)
{
if(SMin.top == SMin.base)
return FALSE;
*e = *(SMin.top - 1);
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: