1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include<iostream> using namespace std; #define MaxSize 20 typedef struct { char data[MaxSize]; int top; }SqStack; bool initStack(SqStack &s){ s.top = -1; } bool push(SqStack &s,char e){ if(s.top==MaxSize-1) return false; s.data[++s.top] = e; return true; } bool pop(SqStack &s,char &e){ if(s.top == -1) return false; e = s.data[s.top--]; return true; } bool Empty(SqStack s){ if(s.top == -1) return true; else return false; } bool brackCheck(char str[],int length){ SqStack s; if(initStack(s)) cout<<"initStack yes\n"; else { cout<<"initStack error\n"; return false; } for(int i=0;i<length;i++){ if(str[i]=='(' || str[i]=='{' || str[i]=='[') { push(s,str[i]); } else { char topELem; if(!pop(s,topELem)) return false; if(str[i]==')' && topELem!='(') return false; if(str[i]=='}' && topELem!='{') return false; if(str[i]==']' && topELem!='[') return false; } } return Empty(s); } int main(){ char syntan[] = {'(','(','[','[',']',']',')',')'}; int length = 8; if(brackCheck(syntan,length)) cout<<"correct\n"; else cout<<"not correct\n"; return 0; }
|