假设一个括号表达式可以包含3种括号:(),{},[],它们可按任意次序嵌套,编写判断表达式中括号是否正确匹配的程序。
若正确匹配输出yes,否则输出no。
#include<stdio.h> #include<string.h> #include<stdlib.h> typedef struct stack{ struct stack *top; struct stack *bottom; struct stack *next; char sign; }stack; void init(stack *list){ list->bottom=(stack*)malloc(sizeof(stack)); list->bottom->next==NULL; list->top=list->bottom; } void push(stack *list,char s){ stack *p; p=(stack*)malloc(sizeof(stack)); p->sign=s; p->next=list->top; list->top=p; } void pop(stack *list){ stack *p; p=list->top; list->top=list->top->next; free(p); } int main(){ char a[100]; int i; stack *list; list=(stack*)malloc(sizeof(stack)); init(list); scanf("%s",&a); for(i=0;i<strlen(a);i++){ if(a[i]=='{'||a[i]=='('||a[i]=='['){ push(list,a[i]); } else if(a[i]=='}'){ if(list->top->sign=='{'){ pop(list); } else{ printf("no\n"); return 0; } } else if(a[i]==')'){ if(list->top->sign=='('){ pop(list); } else{ printf("no\n"); return 0; } } else if(a[i]==']'){ if(list->top->sign=='['){ pop(list); } else{ printf("no\n"); return 0; } } } if(list->top == list->bottom){ printf("yes\n"); return 0; } }