题目要求:
1、输入一串括号,判断是否匹配,如:{()}正确,{(})错误。 2、括号顺序正确。如{()}正确,()[]正确,([])错误
利用链栈实现的该程序。 代码如下:
#include <iostream>
#include"myStack.h"
#include<stdio.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char** argv) {
myStack m;
cout<<"请输入验算符(以#结尾):"<<endl;
char a;
int life=1;
cin>>a;
while(a!='#')
{
switch(a)
{
case'(':if(m.isEmpty())
{
m.push(a);
break;
}
else
{
if(m.getTop()!='(')
{
m.push(a);
break;
}
else
{
life=0;
break;
}
}
case'[':if(m.isEmpty())
{
m.push(a);
break;
}
else
{
if(m.getTop()=='{')
{
m.push(a);
break;
}
else
{
life=0;
break;
}
}
case'{':if(m.isEmpty())
{
m.push(a);
break;
}
else
{
life=0;
break;
}
case')':if(m.getTop()=='(')
{
m.pop();
life=1;
break;
}
else{
life=0;
break;
}
case']':if(m.getTop()=='[')
{
m.pop();
life=1;
break;
}
else{
life=0;
break;
}
case'}':if(m.getTop()=='{')
{
m.pop();
life=1;
break;
}
else{
life=0;
break;
}
}
if(life==0)
{
cout<<"符号不匹配.";
break;
}
cin>>a;
}
if(life==1)
{
cout<<"括号匹配。";
}
return 0;
}