题目:假设一个数学算式中包括圆括号"()",方括号”[]"和花括号“{}”三种类型,编写一算法判断表达式的括号是否配对。
分析:检验括号是否配对可以设置一个栈,每读入一个括号,如果是左括号,则直接进栈,如果读入的是右括号,并且与当前栈顶的左括号是同类型的,则说明括号是配对的,将栈顶的左括号出栈,否则不配对。如果输入序列已经读完,而栈中仍然有等待配对的左括号,则该括号不配对。关于链栈的实现方式参考http://blog.csdn.net/tongxinhaonan/article/details/26614899
程序实现如下:
#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include "string.h"
/*宏定义和链栈类型定义*/
typedef char DataType;
#include "LinkStack.h" //包括链栈实现文件
int Match(DataType e,DataType ch); //检验括号是否配对函数
int main()
{
LinkStack S;
char *p;
DataType e;
DataType ch[60];
InitStack(&S); //初始化链栈
printf("请输入带括号的表达式");
gets(ch);
p=ch;
while(*p)
{
switch(*p)
{
case '(':
case '[':
case '{':
PushStack(S,*p++);
break;
case ')':
case ']':
case '}':
if (StackEmpty(S))
{
printf("缺少左括号。\n");
return 0;
}
else
{
GetTop(S,&e);
if (Match(e,*p))
{
PopStack(S,&e);
}
else
{
printf("左括号不配对\n");
return 0;
}
}
default: //如果是其他字符,则不处理,直接指向下一个字符
p++;
}
}
if (StackEmpty(S))
{
printf("括号匹配\n");
return 1;
}
else
{
printf("缺少右括号\n");
return 0;
}
}
int Match(DataType e,DataType ch)
{
if (e=='('&&ch==')')
{
return 1;
}
else if (e=='['&&ch==']')
{
return 1;
}
else if (e=='{'&&ch=='}')
{
return 1;
}
else
{
return 0;
}
}