3.19 假设一个算术表达式中可以包含三种括号:圆括号“( ”和“ )”、方括号“[”和“]”及花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用。编写判别给定表达式中所含括号是否正确配对出现的算法(已知表达式已存入数据元素为字符的顺序表中)。
1 #include<stdio.h> 2 typedef struct{ 3 char array[50]; 4 int top; 5 }SeqStack; 6 void Inite(SeqStack*S) 7 { 8 S->top=-1; 9 } 10 char Pop(SeqStack*S) 11 { 12 char e; 13 e=S->array[S->top]; 14 S->top--; 15 return e; 16 } 17 void Push(SeqStack*S,char e) 18 { 19 S->top++; 20 S->array[S->top]=e; 21 } 22 void Create(SeqStack*S) 23 { 24 char e; 25 SeqStack*T=S; 26 Inite(T); 27 e=getchar(); 28 while(e!='\n') 29 { 30 Push(T,e); 31 e=getchar(); 32 } 33 } 34 int Empty(SeqStack*S) 35 { 36 if(S->top==-1)return 1; 37 else return 0; 38 } 39 int Match(char a,char b) 40 { 41 switch(a) 42 { 43 case'(':{if(b==')')return 1;} 44 case'[':{if(b==']')return 1;} 45 case'{':{if(b=='}')return 1;} 46 } 47 return 0; 48 } 49 int Judge(SeqStack*S) 50 { 51 char e; 52 SeqStack S1,*T=S; 53 Inite(&S1); 54 while(!Empty(T)) 55 { 56 e=Pop(T); 57 if(e==')'||e==']'||e=='}')Push(&S1,e); 58 else if(e=='('||e=='['||e=='{') 59 { 60 if(Empty(&S1))return 0; 61 else if(!Match(e,Pop(&S1)))return 0; 62 } 63 } 64 if(!Empty(&S1))return 0; 65 return 1; 66 } 67 68 69 int main() 70 { 71 SeqStack str; 72 Create(&str); 73 if(Judge(&str)) 74 printf("yes"); 75 else printf("no"); 76 return 0; 77 }