struct _stack{
    int *data;
    int top;
    int size;
};

typedef struct _stack stack;

stack * new_stack(int size)
{
    stack *hd = (stack*)malloc(sizeof(stack));
    hd->top = -1;
    hd->size = size;
    hd->data = (int*)malloc(size*sizeof(int));
    
    return hd;
}

void push(stack *hd, int x)
{
    if(hd->top == hd->size - 1)
    {
        hd->size += 100;
        int *tmp = (int*)malloc((hd->size)*sizeof(int));
        memcpy(tmp,hd->data,(hd->top + 1)*sizeof(int));
        
        free(hd->data);
        hd->data = tmp;
    }
    
    hd->data[++hd->top] = x;
}

int top(stack *hd)
{
    if(hd->top >= 0)    return hd->data[hd->top];
    return INT_MAX;     //这里容易错。
}

void pop(stack *hd)
{
    if(hd->top >= 0)    hd->top --;
}

void del_stack(stack *hd)
{
    free(hd->data);
    free(hd);
}
typedef struct {
    stack *st1;
    stack *st2;
    int min;
    
} MinStack;

/** initialize your data structure here. */
MinStack* minStackCreate(int maxSize) {
    MinStack * hd = (MinStack*)malloc(sizeof(MinStack));
    
    hd->min = INT_MAX;
    hd->st1 = new_stack(100);
    hd->st2 = new_stack(100);
    
    return hd;
}

void minStackPush(MinStack* hd, int x) {
    
    push(hd->st1,x);
    
    if(x <= hd->min) 
    {
        hd->min = x;
        push(hd->st2, x);
    }
}

void minStackPop(MinStack* hd) {
    int x = top(hd->st1);
    
    pop(hd->st1);
    
    if(x == hd->min)
    {
        pop(hd->st2);
        hd->min = top(hd->st2);
    }
}

int minStackTop(MinStack* hd) {
    return top(hd->st1);
}

int minStackGetMin(MinStack* hd) {
    return hd->min;
}

void minStackFree(MinStack* hd) {
    del_stack(hd->st1);
    del_stack(hd->st2);
    free(hd);
}

/**
 * Your MinStack struct will be instantiated and called as such:
 * struct MinStack* obj = minStackCreate(maxSize);
 * minStackPush(obj, x);
 * minStackPop(obj);
 * int param_3 = minStackTop(obj);
 * int param_4 = minStackGetMin(obj);
 * minStackFree(obj);
 */

 

posted on 2017-12-19 18:05  newbird2017  阅读(120)  评论(0编辑  收藏  举报