Share my c code, using stack


  • 0
    K

    typedef struct Stack
    {
    char *element;
    int size;
    int top;
    }Stack;

    void StackInit(Stack *stack, int size) {

    if (stack == NULL) 
        return;
    
    stack->element = (char*)malloc(sizeof(char) * size);
    stack->size = size;
    stack->top = 0;
    

    }

    bool StackPush(Stack *stack, char val) {

    if (stack == NULL || stack->top + 1 == stack->size)
        return false;
    
    stack->element[++stack->top] = val;
    return true;
    

    }

    char StackPop(Stack *stack) {
    if (stack == NULL || stack->top == 0)
    return '\0';

    return stack->element[stack->top--];
    

    }

    char StackPeek(Stack *stack) {

    if (stack == NULL)
        return '\0';
        
    return stack->element[stack->top];
    

    }
    bool StackEmpty(Stack *stack) {

    return (stack != NULL) && (stack->top == 0);
    

    }

    void StackRelease(Stack *stack) {

    if (stack != NULL) {
        free(stack->element);
        stack->size = 0;
        stack->top = 0;
    }
    

    }

    bool CompareBracket(char a, char b) {

    return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}');
    

    }

    bool isValid(char* s) {

    if (s == NULL) 
        return false;
        
    Stack stack_in, stack_out;
    int len = strlen(s);
    bool result;
    
    StackInit(&stack_in, len + 1);
    StackInit(&stack_out, len + 1);
    
    while (*s != '\0') {
        StackPush(&stack_in, *s);
        s++;
    }
    
    while (!StackEmpty(&stack_in)) {
        char check = StackPop(&stack_in);
        
        if (!StackEmpty(&stack_in) && CompareBracket(check, StackPeek(&stack_in))) {
            StackPop(&stack_in);
        }
        else if (!StackEmpty(&stack_out) && CompareBracket(check, StackPeek(&stack_out))) {
            StackPop(&stack_out);
        }
        else {
            StackPush(&stack_out, check);
        }
    }
    
    result = StackEmpty(&stack_out);
    StackRelease(&stack_in);
    StackRelease(&stack_out);
    
    return result;
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.