顺序栈判断表达式的括号匹配
代码如下:
#include <iostream>
using namespace std;
typedef struct sqstack //顺序栈定义
{
char data[10];
int top;
}Sqstack;
void initstack(struct sqstack &Sqstack) //初始化栈
{
Sqstack.top=-1;
}
int isempty(struct sqstack &Sqstack) //判断栈是否空
{
if(Sqstack.top==-1)
{
cout<<" 顺序栈为空 "<<endl;
return 1;
}
else
{
cout<<" 顺序栈不为空 "<<endl;
}
return 0;
}
int push(struct sqstack &Sqstack,char x) //插入元素x作为新的栈顶元素
{
if(Sqstack.top==9)
{
cout<<" 错误 "<<endl;
return 0;
}
Sqstack.top=Sqstack.top+1;
Sqstack.data[Sqstack.top]=x;
return 1;
}
int gettop(struct sqstack Sqstack,char &e)//得到栈顶元素的值
{
if(Sqstack.top==-1)
{
cout<<" NULL(空表) "<<endl;
return 0;
}
e=Sqstack.data[Sqstack.top];
return 1;
}
int pop(struct sqstack &Sqstack,char &x)//删除栈顶元素并用x返回它
{
if(Sqstack.top==-1)
{
return 0;
}
x=Sqstack.data[Sqstack.top];
Sqstack.top=Sqstack.top-1;
return 1;
}
int ifmatch(char exp[],int n)//从字符串中读取元素,
//若为左括号则将它压进栈中再读取到右括号则将出栈(消除一对括号),重复此步骤直到读完字符串。若栈为空说明一对对括号消除即括号匹配,若不为空说明右括号比左括号多即不匹配
//若为右括号则直接说明不匹配
{
struct sqstack stack;//结构体栈创建实例
initstack(stack);//初始化
int i;int x;
for(i=0;i<n;i++)
{
if(exp[i]=='(')
{push(stack,'(');}
if(exp[i]==')')
{
if(isempty==1)//栈空且只有右括号说明不匹配
{return 0;}
else
{pop(stack,x);}
}
}
if(isempty==1)//栈空说明括号一对对消除则匹配
{return 1;}
else
{return 0;}//栈不空说明站内还剩下未消除的左括号则不匹配
}
int main()
{
char exp[100];
int i=0;
cout<<"请输入表达式:";
cin>>exp;
while(exp[i]!='\0')//求输入的字符串长度
{i++;}
if(ifmatch(exp,i)==1)
{cout<<"匹配";}
else
{cout<<"不匹配";}
return 0;
}
运行结果如下: