为简单起见,仅考虑小括号。
思路:
在读到‘#’之前,不断读入字符,若是左括号,则进入处理括号的函数(该函数若读到左括号则进入自身下一层,若读到右括号则退出,若读到#则说明左括号过多);若是右括号,则说明右括号过多。
#include <stdio.h>
#include <stdlib.h>
void parenthese();
int main(void)
{
printf("Input the expression:\n");
char ch = getchar();
while (ch != '#')
{
if (ch == '(')
{
parenthese();
}
else if (ch == ')')
{
printf("Redundant right parenthese!\n");
exit(0);
}
ch = getchar();
}
printf("Correct!\n");
return 0;
}
void parenthese()
{
char ch = getchar();
while ((ch != '#'))
{
if (ch == '(')
parenthese();
else if (ch == ')')
return;
ch = getchar();
}
printf("Redundant left parenthese!\n");
exit(0);
}
总结:
本质上函数递归调用中,开辟运行空间是压栈,函数退出释放空间是弹栈;相较于迭代程序中用户自己定义的栈,函数递归是利用系统中的栈操作,压栈和弹栈的操作是由系统中函数调用与返回操作自动完成的。