括号匹配

来源:互联网 发布:车辆控制数据采集 编辑:程序博客网 时间:2024/04/30 13:55

题目描述:假设表达式中允许包含三种括号:圆括号、方括号和大括号。编写一个算法判断表达式中的括号是否正确匹配。

代码:

#include<stdio.h>#include<malloc.h>#include<string.h>#define MaxSize 100typedef char ElemType;typedef struct {ElemType data[MaxSize];int top;}SqStack;//初始化栈void InitStack(SqStack *&s){s=(SqStack *)malloc(sizeof(SqStack));s->top=-1;}//销毁栈void DestroyStack(SqStack *s){free(s);}//判空bool StackEmpty(SqStack *s){return(s->top==-1);}//进栈bool Push(SqStack *s,ElemType e){if(s->top==MaxSize-1)return false;s->top++;s->data[s->top]=e;return true;}//出栈bool Pop(SqStack *s,ElemType &e){if(-1==s->top)return false;e=s->data[s->top];s->top--;return true;}//得到栈顶元素bool GetTop(SqStack *s,ElemType &e){if(-1==s->top)return false;e=s->data[s->top];return true;}//判断是否匹配bool Match(SqStack *s,char exp[],int n){int i=0;char e;bool match=true;    InitStack(s);while(i<n && match){if('('==exp[i] || '['==exp[i] || '{'==exp[i])Push(s,exp[i]);else if(')'==exp[i] || ']'==exp[i] || '}'==exp[i]){if(GetTop(s,e)==true){if((e=='(' && ')'==exp[i]) ||(e=='[' &&']'==exp[i]) ||(e=='{' &&'}'==exp[i]) )Pop(s,e);else  match=false;}elsematch=false;}i++;}if(!StackEmpty(s))match=false;DestroyStack(s);return match;}void main(){SqStack *s;int b;char a[100]="{(1+2)*[2.5]}";b=strlen(a);if(Match(s,a,b))printf("匹配"); else printf("不匹配");}

0 0
原创粉丝点击