题目描述:假设表达式中允许包含三种括号:圆括号、方括号和大括号。编写一个算法判断表达式中的括号是否正确匹配。
代码:
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#define MaxSize 100
typedef 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;
}
else
match=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("不匹配");
}