int Matching( void ) {Stack S; InitStack( S ); int flag = 1; char ch; scanf(“%c”, &ch ); while( ch!=‘#’ && flag ){ switch( ch){ case ‘[‘: case ‘(‘: push( S, ch ); break; case ‘)’: if( !StackEmpty(S)&&GetTop(S)==‘(‘ ) pop(S,x); else flag = 0; break; case ‘]’: if( !StackEmpty(S)&&GetTop(S)==‘[‘ ) pop(S,x); else flag = 0; break; } scanf(“%c”, &ch ); } if (StackEmpty( S ) && flag) return 1; else return 0; } void main( ) { int i; i = Matching( ); if( i==1 ) printf(“匹配!”); else printf(“不匹配!”); } 改进匹配函数(函数另外命名),使之能通过返回值进行更细致的区分:1表示正确、0表示交叉错误、-1表示右边多、-2表示左边多。
时间: 2024-03-22 17:37:30 浏览: 15
可以参考下面的代码实现改进后的匹配函数:
```
int Matching(void) {
Stack S;
InitStack(S);
char ch, x;
int flag = 1, result = 1, count_left = 0, count_right = 0;
scanf("%c", &ch);
while (ch != '#' && flag) {
switch (ch) {
case '[':
case '(':
Push(S, ch);
count_left++;
break;
case ')':
if (!StackEmpty(S) && GetTop(S, x) && x == '(') {
Pop(S, x);
count_right++;
} else {
flag = 0;
result = -1;
}
break;
case ']':
if (!StackEmpty(S) && GetTop(S, x) && x == '[') {
Pop(S, x);
count_right++;
} else {
flag = 0;
result = -2;
}
break;
}
scanf("%c", &ch);
}
if (!StackEmpty(S) && flag) {
result = 0;
} else if (count_left != count_right && flag) {
result = 0;
}
return result;
}
```
增加了计数变量 `count_left` 和 `count_right`,用于记录左括号和右括号的数量,以便判断左右括号数量是否相等。同时,根据题目要求,修改了返回值的意义,通过不同的返回值表示不同的匹配结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![.pdf](https://img-home.csdnimg.cn/images/20210720083646.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)