栈的应用


#include 

#define MaxSize 10

typedef struct {
    char data[MaxSize];
    int top;
} SqStack;

void InitStack(SqStack *s) {
    s->top = -1;
}

int Push(SqStack *s, char e) {
    if (s->top == MaxSize - 1) return -1;
    s->data[++s->top] = e;
    return 1;
}

int Pop(SqStack *s, char *e) {
    if (s->top == -1) return -1;
    *e = s->data[s->top--];
    return 1;
}

int Empty(SqStack s) {
    return s.top == -1;
}

int bracketCheck(char str[], int length) {
    SqStack s;
    InitStack(&s);
    for (int i = 0; i < length; i++) {
        if (str[i] == '(' || str[i] == '[' || str[i] == '{') {
            Push(&s, str[i]);
        } else {
            if (Empty(s)) return -1;
            char topElem;
            Pop(&s, &topElem);
            if (str[i] == ')' && topElem != '(') return -1;
            if (str[i] == ']' && topElem != '[') return -1;
            if (str[i] == '}' && topElem != '{') return -1;
        }
    }
    return Empty(s);
}

int main() {
    char str[] = "{(())[]}";
    printf("%i\n", bracketCheck(str, 8));
    return 0;
}

你可能感兴趣的:(栈的应用)