用堆栈写一段c代码检查一段代码中“/**/”符号是否匹配
时间: 2023-12-04 08:04:42 浏览: 36
下面是一段用堆栈检查代码中注释符号是否匹配的示例代码(C 实现):
```c
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
bool checkComment(char* code) {
int len = strlen(code);
char s[len];
int top = -1;
for (int i = 0; i < len; i++) {
char c = code[i];
if (c == '/' && i > 0 && code[i-1] == '*') {
// 弹出栈顶元素,判断是否为 '/'
if (top >= 0 && s[top] == '/') {
top--;
} else {
return false;
}
} else if (c == '*' && i > 0 && code[i-1] == '/') {
// 将 '/*' 压入栈中
s[++top] = '/';
}
}
// 如果栈为空,则说明注释符号匹配
return top == -1;
}
int main() {
char code1[] = "int main() { /* Hello, world! */ }";
char code2[] = "int main() { /* Hello, world! */";
char code3[] = "int main() { */ Hello, world! /* }";
printf("%d\n", checkComment(code1)); // 输出 1
printf("%d\n", checkComment(code2)); // 输出 0
printf("%d\n", checkComment(code3)); // 输出 0
return 0;
}
```
在这个示例代码中,checkComment 函数用于检查代码中的注释符号是否匹配。它首先创建一个字符数组 s 作为栈,并遍历代码中的每个字符。如果遇到 '/*',则将 '/' 压入栈中;如果遇到 '*/',则从栈顶弹出一个元素,判断是否为 '/',如果是,则注释符号匹配,继续遍历;否则不匹配,返回 false。最后,如果栈为空,则说明注释符号匹配,返回 true;否则不匹配,返回 false。
在 main 函数中,我们分别测试了三个代码片段,其中 code1 是注释符号匹配的,code2 和 code3 分别是注释符号不匹配的两种情况。输出结果分别为 1、0 和 0,符合预期。