括号匹配(栈的应用)

    技术2024-10-30  24

    #include<stdio.h> #define MaxSize 256 //栈的相关操作 typedef struct{ //定义栈 char data[MaxSize]; int top; }SqStack; void InitStack(SqStack &S){ //初始化 S.top = -1; } bool IsEmpty(SqStack S){ //判空 if(S.top == -1) return true; else return false; } bool Push(SqStack &S,char c){ //入栈 if(S.top == MaxSize-1) return false; S.data[++S.top] = c; return true; } bool Pop(SqStack &S,char &c){ //出栈 if(S.top == -1) return false; c = S.data[S.top--]; return true; } /*括号匹配*/ bool BracketsCheck(char *str){ char e; SqStack S; InitStack(S); int i = 0; while(str[i] != '\0'){ switch(str[i]){ //左括号入栈 case '(':Push(S,'(');break; case '[':Push(S,'[');break; case '{':Push(S,'{');break; //遇到右括号,检测栈顶 case ')':Pop(S,e); if(e != '(') return false; break; case ']':Pop(S,e); if(e != '[') return false; break; case '}':Pop(S,e); if(e != '{') return false; break; default: break; }//switch i++; }//while if(!IsEmpty(S)){ printf("Check error!\n"); return false; } else{ printf("Check right.\n"); return true; } } int main(){ char str[MaxSize] = {'(','(','{','[',']','}',')',')'}; BracketsCheck(str); return 0; }
    Processed: 0.009, SQL: 9