#include<iostream>
#include<cstdio>
#define MAXSIZE 100
#define OK 1
#define ERROR 0
using namespace std;
typedef struct //定义栈
{
char *base;
char *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S) //初始化栈
{
S.base=new char[MAXSIZE];
if(!S.base) return 0;
S.top=S.base;
S.stacksize=MAXSIZE;
return OK;
}
int Push(SqStack &S,char e) //压栈
{
if(S.top-S.base==S.stacksize) return ERROR;
*S.top++=e;
return OK;
}
int Pop(SqStack &S,char &e) //出栈
{
if(S.top==S.base) return ERROR;
e=*--S.top;
return OK;
}
/*int StackEmpty(SqStack &S)
{
if(S.top==S.base) return 1;
else return 0;
}*/
char GetTop(SqStack S) //取栈顶元素
{
if(S.top!=S.base)
return *(S.top-1);
}
int Matching(SqStack &S) //检验括号是否匹配
{
char ch,x;
int flag=1;
cin>>ch;
while(ch!='#'&&flag)
{
switch(ch)
{
case '(':
case '[':
Push(S,ch);
break;
case ']':
if((S.top!=S.base)&&GetTop(S)=='[')
Pop(S,x);
else flag=0;
break;
case ')':
if((S.top!=S.base)&&GetTop(S)=='(')
Pop(S,x);
else flag=0;
break;
}
cin>>ch;
}
if((S.top==S.base)&&flag) cout<<"success"<<endl;
else cout<<"failed"<<endl;
return 0;
}
int main()
{
SqStack S;
InitStack(S);
Matching(S);
return 0;
}
括号匹配的检验
最新推荐文章于 2024-04-10 21:02:17 发布