定义栈的数据结构,要求添加一个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));
}