c语言实现括弧匹配检测
时间: 2023-11-24 17:08:23 浏览: 91
以下是C语言实现括号匹配检测的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct Stack {
char data[MAX_SIZE];
int top;
} Stack;
void push(Stack *s, char c) {
if (s->top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
exit(1);
}
s->data[++(s->top)] = c;
}
char pop(Stack *s) {
if (s->top < 0) {
printf("Stack Underflow\n");
exit(1);
}
return s->data[(s->top)--];
}
char peek(Stack *s) {
if (s->top < 0) {
printf("Stack Underflow\n");
exit(1);
}
return s->data[s->top];
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_balanced(char *expr) {
Stack s;
s.top = -1;
for (int i = 0; expr[i] != '\0'; i++) {
char c = expr[i];
switch (c) {
case '(':
case '{':
case '[':
push(&s, c);
break;
case ')':
if (is_empty(&s) || pop(&s) != '(') {
return 0;
}
break;
case '}':
if (is_empty(&s) || pop(&s) != '{') {
return 0;
}
break;
case ']':
if (is_empty(&s) || pop(&s) != '[') {
return 0;
}
break;
default:
break;
}
}
return is_empty(&s);
}
int main() {
char expr[MAX_SIZE];
printf("Enter an expression: ");
fgets(expr, MAX_SIZE, stdin);
if (is_balanced(expr)) {
printf("The expression is balanced\n");
} else {
printf("The expression is not balanced\n");
}
return 0;
}
```
代码中使用了一个栈来存储左括号,当遇到右括号时,从栈中取出一个左括号来匹配。如果遇到非括号字符,则忽略。最后,如果栈为空,则表示括号匹配成功。否则,表示括号不匹配。
阅读全文