MiniStack(找栈中最小元素的栈)

MiniStack(找栈中最小元素的栈)

  (2012-09-22 20:07:39)
标签: 

面试题

 

算法设计

 

c/c语言

 

杂谈

分类: 一些面试题

 

    程序名:能查找栈中最小元素的栈
    实现功能:
            1、出栈、进栈、输出栈中最小元素的时间复杂度都是O(1);
            2、新元素进栈之后,若小于原最小元素,则打印最小元素
            改变信息;

 

 

#include
#include
#define datatype char

typedef struct
{
        datatype Elem;
        datatype Min;
}ElemType;


typedef struct
{
        ElemType *StElem;
        int size;
        int top;
}Stack;


void Stack_Init(Stack &St , int StSize)
{
        St.StElem = (ElemType *)malloc(sizeof(ElemType) * StSize);
        St.top = -1;
        St.size = StSize;
}

void Stack_Pop(Stack &St , datatype &E)
{
        if(St.top == -1)
                perror("The Stack is Empty , Pop Error !\n");

        E = St.StElem[St.top].Elem;
        St.top--;
        printf("Pop Elem '%c' Succeed !\n",E);
}

void Stack_Push(Stack &St , datatype E)
{
        if(St.top == St.size - 1)
                perror("The Stack is Full , Push Error !\n");

        St.top++;
        St.StElem[St.top].Elem = E;
        St.StElem[St.top].Min = (St.top == 0?E:St.StElem[St.top - 1].Min);
        printf("Push New Elem '%c' into Stack Succeed !\n",E);
        if(St.StElem[St.top].Min > E)
        {
                St.StElem[St.top].Min = E;
                printf("The New Min Elem in the Stack is '%c'\n",E);
        }
}

void Min_Find(Stack St , datatype &E)
{
        if(St.top == -1)
                perror("The Stack is Null , Error !\n");

        E = St.StElem[St.top].Min;
}

void Stack_Free(Stack &St)
{
        free(St.StElem);
        St.StElem = NULL;
}

int main()
{
        int sec;
        datatype E;
        Stack Stk;
        Stack_Init(Stk,20);
        Stack_Push(Stk,'A');
        Stack_Push(Stk,'B');
        Stack_Push(Stk,'8');
        Stack_Push(Stk,'7');
        Min_Find(Stk,E);
        printf("The Min Elem in The Stack is '%c'\n",E);
        Stack_Pop(Stk,E);
        Min_Find(Stk,E);
        printf("The Min Elem in The Stack is '%c'\n",E);
        Stack_Pop(Stk,E);
        Min_Find(Stk,E);
        printf("The Min Elem in The Stack is '%c'\n",E);
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值