括號分配(棧和佇列)C
阿新 • • 發佈:2018-12-26
1、注意括號匹配問題
2、只需提交你所編寫的演算法
#include <stdio.h> #define Max 105 typedef struct { char date[Max]; int top; } Spstack; void InitStack(Spstack *&s) { s= new Spstack; s->top=-1; } bool StackEmpty(Spstack *s) { return(s->top==-1); } bool Push(Spstack *&s,char e) { if(s->top==Max-1)return false; s->top++; s->date[s->top]=e; return true; } bool GetTop(Spstack *s,char &e) { if(s->top==-1)return false; e=s->date[s->top]; return true; } bool Pop(Spstack *&s,char &e) { if(s->top==-1)return false; e=s->date[s->top]; s->top--; return true; } void DestroyStack(Spstack * &s) { delete(s); }int solve(char *a,Spstack *st) { int i=0; char e; int match=1; while(a[i]!='\0'&&match) { if(a[i]=='('||a[i]=='['||a[i]=='{') Push(st,a[i]); else if(a[i]==')'||a[i]==']'||a[i]=='}') { if(a[i]==')'&&GetTop(st,e)==true) { if(e!='(') match=false; else Pop(st,e); } else if(a[i]==']'&&GetTop(st,e)==true) { if(e!='[') match=false; else Pop(st,e); } else if(a[i]=='}'&&GetTop(st,e)==true) { if(e!='{') match=false; else Pop(st,e); } else match=0; } i++; } if(!StackEmpty(st)) match=0; return match; } int main() { char a[100]; bool match; Spstack *st; InitStack(st); gets(a); match=solve(a,st); DestroyStack(st); if(match)printf("Yes\n"); else printf("No\n"); return 0; }