题目要求:
我的代码实现:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MaxSize 100
#define ElemType char
typedef struct{
ElemType data[MaxSize];
int top;
}Stack;
void InitStack(Stack &S)
{
memset(S.data,'\0',MaxSize);
S.top=0;
}
bool Push(ElemType e,Stack &S)
{
if(S.top==(MaxSize-1))return false;
S.data[S.top]=e;
S.top++;
return true;
}
bool Pop(Stack &S,ElemType &e)
{
if(S.top==0)return false;
e=S.data[--S.top];
return true;
}
bool StackEmpty(Stack &S)
{
if(S.top==0)return true;
else return false;
}
void Judge(char s[]) //将此括号序列作为一个字符串输入
{
Stack S;
InitStack(S); //初始化栈
ElemType c; //用来保存出栈元素
for(unsigned int i=0;i<strlen(s);i++)
{
if(s[i]=='{'||s[i]=='['||s[i]=='(')
{
Push(s[i],S); //只要是左括号就入栈处理
}
else if(s[i]=='}'||s[i]==')'||s[i]==']')//如果是右括号
{
if(StackEmpty(S)) //如果没有左括号和它匹配,就是不合格
{
printf("\n括号不匹配!\n");
exit(0);
}
Pop(S,c);
if((s[i]=='}'&&c!='{')||(s[i]==')'&&c!='(')||(s[i]=='['&&c!=']')) //判断出栈的左括号和当前右括号能否成对
{
printf("\n括号不匹配!\n");
exit(0);
}
}
}
if(!StackEmpty(S)) //判断是否还有剩余左括号
{
printf("\n括号不匹配!\n");
exit(0);
}
printf("\n括号匹配\n");
}
int main()
{
char s[100];
printf("\n输入括号的表达式:\n");
scanf("%s",s);
Judge(s);
return 0;
}