[Question] P165 sword refers to offer: Interview question 30: Stack containing min function (using pointers is not implemented)

Interview Question 30: Stack containing min function
Define the data structure of the stack. Please implement a min function that can get the smallest element of the stack in this type. In this stack, the time complexity of calling min, push, and pop is all O(1).

Innovation point: The pointer in the MinStack structure is not a stack. You only need to change the pointer point when you pop out of the stack . There is no need to pop up the top element
of the stack and click the link: https://leetcode-cn.com/problems/bao-han-minhan-shu -de-zhan-lcof/

typedef struct
{
    
    
    // 结构体里的是指针不是一个栈
    int* data_stack;
    int* min_stack;
    int data_index;
    int min_index;
} MinStack;

/** initialize your data structure here. */

MinStack* minStackCreate()
{
    
    
    MinStack* p = (MinStack*)malloc(sizeof(MinStack));
    p -> data_stack = (int*)malloc(sizeof(int) * 20000);
    p -> min_stack = (int*)malloc(sizeof(int) * 20000);
    p -> data_index = 0;
    p -> min_index = 0;
    return p;
}

int minStackTop(MinStack*);

void minStackPush(MinStack* obj, int x)
{
    
    
    (obj -> data_stack)[obj -> data_index++] = x;
    if(obj -> min_index == 0 || x < (obj -> min_stack)[obj -> min_index - 1])
        (obj -> min_stack)[obj -> min_index++] = x;
    else
        (obj -> min_stack)[obj -> min_index++] = (obj -> min_stack)[obj -> min_index - 1];
}

// 最值得学习的就是出栈只需改指针指向,无需删除值
void minStackPop(MinStack* obj)
{
    
    
    if(obj -> data_index > 0)
    {
    
    
        obj -> data_index--;
        obj -> min_index--;
    }
}

int minStackTop(MinStack* obj)
{
    
    
        return (obj -> data_stack)[obj -> data_index - 1];
}

int minStackMin(MinStack* obj)
{
    
    
        return (obj -> min_stack)[obj -> min_index - 1];
}

void minStackFree(MinStack* obj)
{
    
    
    free(obj -> data_stack);
    free(obj -> min_stack);
    free(obj);
}

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

Guess you like

Origin blog.csdn.net/m0_46613023/article/details/115005626