1、设计原理:
主要是利用了栈的结构,在表达式的输入过程中实现对括号是否匹配的判断。根据其括号的原则:小括号之中不能含有大括号或中括号,中括号中不能含有大括号。再由紧密性,左边括号和右边括号是紧密相连的。否则判断为错。 其操作为:每输入一个字符打一下回车,若输入括号顺序错误则跳出,并显示错误!
2、例程:
#include
#define MAX 100
#define TRUE 1
#define FALSE 0
#define E a
typedef struct transition /*建立一个栈*/
{
char sq[MAX];
int top;
}sqstack;
sqstack bt;
int emptysqstack(sqstack bt) /*判栈空*/
{
if(bt.top==-1)
return TRUE;
else
return FALSE;
}
void pushsqstack(sqstack bt,char sh) /*入栈*/
{
if(bt.top==MAX-1)
{
printf("over flow");
exit(0);
}
bt.top++;
bt.sq[bt.top]=sh;
}
void popsqstack(sqstack bt) /*出栈*/
{
int sh;
if(bt.top==-1)
{
printf("empty");
exit(0);
}
sh=bt.sq[bt.top];
bt.top--;
return sh;
}
Search(sqstack bt) /*查找括号是否匹配*/
{
char c=0;
printf("If you want to break,please input 'a'\n");
while(c!=E&&bt.top<=MAX&&c!='('&&c!='['&&c!='{')
{
c=getchar();
pushsqstack(bt,c);
}
SearchA(bt,c);
SearchB(bt,c);
SearchC(bt,c);
}
SearchA(sqstack bt,char c) /*查找小括号是否匹配*/
{
if(c=='(')
{
while(c!=')'&&c!='['&&c!=']'&&c!='{'&&c!='}')
{
c=getchar();
pushsqstack(bt,c);
}
if(c=='(')
printf("right\n");
else if(c=='['||c==']'||c=='{'||c=='}')
printf("wrong\n");
}
}
SearchB(sqstack bt,char c) /*查找中括号是否匹配*/
{
if(c=='[')
while(c!=']'&&c!='('&&c!=')'&&c!='{'&&c!='}')
{
c=getchar();
pushsqstack(bt,c);
}
if(c==')'||c=='{'||c=='}')
printf("wrong\n");
else if(c=='(')
SearchA(bt,c);
else if(c==']')
printf("right\n");
else
printf("wrong\n");
}
SearchC(sqstack bt,char c) /*查找大括号是否匹配*/
{
if(c=='{')
while(c!='}'&&c!='['&&c!=']'&&c!='('&&c!=')')
{
c=getchar();
pushsqstack(bt,c);
}
if(c==']'||c==')')
printf("wrong\n");
else if(c=='[')
SearchB(bt,c);
else if(c=='(')
SearchA(bt,c);
else if(c=='}')
printf("right\n");
else
printf("wrong\n");
}
main()
{
int i;
bt.top=-1;
i=emptysqstack(bt);
if(i)
{
Search(bt);
}
else
exit(0);
}