Untitled

 avatar
unknown
c_cpp
2 years ago
2.2 kB
6
Indexable
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define SIZE 501

struct StackEl {
    char el;
    struct StackEl *next;
};

struct Stack {
    struct StackEl *top;
    int count;
};

struct Stack* initStack()
{
    struct Stack *new_stack = (struct Stack*)malloc(sizeof(struct Stack));
    new_stack->top = NULL;
    new_stack->count = 0;
    return new_stack;
}

struct StackEl* pop(struct Stack *stack)
{
    if (!stack->top)
        return NULL;
    struct StackEl *r_elem = stack->top;
    stack->top = r_elem->next;
    (stack->count)--;
    return r_elem;
}

void push(struct Stack *stack, char value)
{
    struct StackEl *new_elem = (struct StackEl*)malloc(sizeof(struct StackEl));
    new_elem->el = value;
    new_elem->next = stack->top;
    stack->top = new_elem;
    (stack->count)++;
}

struct StackEl* top(struct Stack *stack)
{
    return stack->top;
}

int isEmpty(struct Stack *stack)
{
    if (stack->top)
        return 0;
    return 1;
}

int count(struct Stack *stack)
{
    return stack->count;
}

int main()
{   
    char input_str[SIZE];
    char cur_sym;
    struct StackEl *prev;
    fgets(input_str, SIZE, stdin);
    struct Stack *sym_stack = initStack();
    for (int i = 0; input_str[i]; i++) {
        cur_sym = input_str[i];
        if (cur_sym == '(' || cur_sym == '[' || cur_sym == '<' || cur_sym == '{') {
            push(sym_stack, cur_sym);
        } else if (cur_sym == ')' || cur_sym == ']' || cur_sym == '>' || cur_sym == '}') {
            prev = pop(sym_stack);
            if (prev) {
                int f_case = (prev->el == '(' && cur_sym == ')');
                int s_case = (prev->el == '[' && cur_sym == ']');
                int t_case = (prev->el == '<' && cur_sym == '>');
                int fo_case = (prev->el == '{' && cur_sym == '}');
                if (!(f_case || s_case || t_case || fo_case)) {
                    printf("wrong\n");
                    return 0;
                }
            } else {
                printf("wrong\n");
                return 0;
            }
        }
    }
    if (isEmpty(sym_stack)) {
        printf("correct\n");
    } else {
        printf("wrong\n");
    }
    return 0;
}
Editor is loading...