括号匹配算法的C语言代码和注释
时间: 2023-05-20 21:07:31 浏览: 105
括号匹配 C语言代码
以下是括号匹配算法的C语言代码和注释:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义栈结构体
typedef struct {
char *data;
int top;
} Stack;
// 初始化栈
Stack *initStack(int size) {
Stack *s = (Stack *)malloc(sizeof(Stack));
s->data = (char *)malloc(size * sizeof(char));
s->top = -1;
return s;
}
// 判断栈是否为空
int isEmpty(Stack *s) {
return s->top == -1;
}
// 判断栈是否满了
int isFull(Stack *s, int size) {
return s->top == size - 1;
}
// 入栈
void push(Stack *s, char c) {
if (isFull(s, sizeof(s->data))) {
printf("Error: stack is full\n");
exit(1);
}
s->data[++s->top] = c;
}
// 出栈
char pop(Stack *s) {
if (isEmpty(s)) {
printf("Error: stack is empty\n");
exit(1);
}
return s->data[s->top--];
}
// 判断是否匹配
int match(char a, char b) {
return (a == '(' && b == ')') || (a == '[' && b == ']') || (a == '{' && b == '}');
}
// 判断表达式中的括号是否匹配
int checkExpression(char *expr) {
Stack *s = initStack(strlen(expr));
int i;
for (i = 0; i < strlen(expr); i++) {
char c = expr[i];
if (c == '(' || c == '[' || c == '{') {
push(s, c);
} else if (c == ')' || c == ']' || c == '}') {
if (isEmpty(s) || !match(pop(s), c)) {
return 0;
}
}
}
return isEmpty(s);
}
// 测试
int main() {
char expr[] = "int main() { if (i > 0) { printf(\"hello world\\n\"); } }";
printf("%s\n", checkExpression(expr) ? "matched" : "not matched");
return 0;
}
```
阅读全文