微软面试2 堆栈

2.设计包含min函数的栈(栈)
定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。

要求函数min、push以及pop的时间复杂度都是O(1)。

这里我采用的是双向链表的方式实现堆栈,min函数设计的时候,一开始想到了设置一个指针指向最小的元素,但是发现当pop的时候,如果最小的元素被pop了,就不是o(1)了,所以最后采用了空间换取效率的方法,就是采用在每个节点上,增加一个域,标识增加这个节点的时候,堆栈的最小值。

代码如下

#include <stdio.h>
#include <malloc.h>
typedef struct Lnode
{
    int data;
    int min;
    struct Lnode *next;
    struct Lnode *front;
}*List;
typedef  struct stack
{
      List tail;
      List list;
      int min;
}*Stack;
int push(Stack s,int i)
{
    List node=(List )malloc(sizeof(struct Lnode));
                node->data=i;
                node->next=NULL;
                node->front=s->tail;
                s->tail->next=node;
                s->tail=node;
                if(i<s->min)
                {
                    s->min=i;
                }
                s->tail->min=s->min;
                return 0;
}
int pop(Stack s)
{
    if(s->tail->front==NULL)
    {
        return -1;
    }
      int res=s->tail->data;
      s->tail=s->tail->front;
      s->tail->next=NULL;
      return res;
}
int init(Stack s)
{
    
    s->list=(List )malloc(sizeof(struct Lnode));
    s->tail=s->list;
    s->min=32567;
}
int min(Stack s)
{
     return s->tail->min;
}
int main()
{
    Stack s=(Stack )malloc(sizeof(struct stack));
    printf("----");
    init(s);
   
    push(s,2);
    push(s,3);
    push(s,6);
     push(s,1);
    printf("%d\n",min(s));
    printf("%d\n",pop(s));
    printf("%d\n",pop(s));
    printf("%d\n",min(s));
    printf("%d\n",pop(s));
    printf("%d\n",pop(s));
    printf("%d\n",pop(s));
    printf("%d\n",pop(s));
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值