Description
假设在表达式中([]())或[([ ][ ])]等为正确的格式,[( ])或([( ))或 (( )])均为不正确的格式。基于栈设计一个判断括号是否正确匹配的算法。
Input
输入数据有多组,每组测试数据一行,一个字符串,只包含 ‘[‘ ,’]’ ,’(‘ ,‘)’ 。
Output
对于每组测试数据,若括号匹配输出yes,否则输出 no。
#include<stdlib.h>
#include<string.h>
#define MaxSize 100
typedef struct
{
char data[MaxSize];
int top;
}SqStack;
void InitSqStack(SqStack &S)
{
S.top=-1;
}
bool Push(SqStack &S,char x)
{
if(S.top==MaxSize-1) return false;
S.data[++S.top]=x;
return true;
}
bool Pop(SqStack &S,char &x)
{
if(S.top==-1) return false;
x=S.data[S.top--];
return true;
}
bool StackEmpty(SqStack S)
{
if(S.top==-1) return true;
else return false;
}
bool IsOK(SqStack &S,char ch[])
{
int i=0;
char x;
for(i=0;i<strlen(ch);i++)
{
if(ch[i]=='('||ch[i]=='[')
{
Push(S,ch[i]);
}
else
{
if(ch[i]==')')
{
Pop(S,x);
if(x!='(') {return false;}
}
if(ch[i]==']')
{
Pop(S,x);
if(x!='[') {return false;}
}
}
}
return StackEmpty(S);
}
int main()
{
SqStack S;
char ch[100];
while(gets(ch)!=NULL)
{
InitSqStack(S);
if(IsOK(S,ch)) printf("yes\n");
else printf("no\n");
}
return 0;
}
为什么我这样写的代码一直报错?
全部评论
(0) 回帖