码迷,mamicode.com
首页 > 编程语言 > 详细

数据结构(C语言) 栈的应用之括号匹配

时间:2019-07-09 16:39:13      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:应用   str   lse   getchar   print   else   tchar   col   --   

#include<stdio.h>
#include<stdlib.h>
typedef struct SqStack {
    char str[100];
    int top;
}SqStack;
void Push(SqStack* S, char c) {
    S->top++;
    S->str[S->top] = c;
}
void Pop(SqStack* S, char* c) {
    *c = S->str[S->top];
    S->top--;
}
int Empty(SqStack* S) {
    return S->top == -1;
}
void Init(SqStack* S) {
    S->top = -1;
}
char LeftBracket(char right) {
    if (right == ))
        return (;
    else if (right == ])
        return [;
    else if (right == })
        return {;
    return 0;
}
int BracketsCheck(char* str) {
    SqStack S;
    Init(&S);
    int i = 0;
    while (str[i] != \0) {
        switch (str[i]) {
        case (:
        case [:
        case {:
            Push(&S, str[i]);
            i++;
            break;
        case ):
        case ]:
        case }:
            if (!Empty(&S)) {
                char c;
                Pop(&S, &c);
                if (c == LeftBracket(str[i]))
                    i++;
                else
                    return 0;
            }
            else
                return 0;
            break;
        default:
            i++;
        }
    }
    return Empty(&S);
}

void main() {
    char* str = "{[1+2*(5-2)]*4*{2+6}}";
    int pass = BracketsCheck(str);
    if (pass) {
        printf("括号匹配!\n");
    }
    else {
        printf("括号不匹配!\n");
    }
    getchar();
}

 

数据结构(C语言) 栈的应用之括号匹配

标签:应用   str   lse   getchar   print   else   tchar   col   --   

原文地址:https://www.cnblogs.com/wumingoo1/p/11158258.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!