假设表达式中允许包含圆括号、方括号和大括号3中括号,编写一个算法判断表达式中括号是否正确配对。用c语言实现
时间: 2024-06-12 12:11:20 浏览: 101
3.19括号配对_园括号包含吗_数据结构_
这里提供一个C语言实现的算法来判断表达式中的括号是否正确配对:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, char c) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int is_match(char left, char right) {
if (left == '(' && right == ')') {
return 1;
} else if (left == '[' && right == ']') {
return 1;
} else if (left == '{' && right == '}') {
return 1;
} else {
return 0;
}
}
int is_balanced(char *exp) {
Stack s;
init(&s);
int i = 0;
while (exp[i] != '\0') {
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') {
push(&s, exp[i]);
} else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') {
if (is_empty(&s)) {
return 0;
}
char left = pop(&s);
if (!is_match(left, exp[i])) {
return 0;
}
}
i++;
}
return is_empty(&s);
}
int main() {
char exp[MAX_SIZE];
printf("Enter an expression: ");
scanf("%s", exp);
if (is_balanced(exp)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}
return 0;
}
```
该算法使用了一个栈来存储左括号,当遇到右括号时,弹出栈顶元素并判断是否匹配。如果匹配,则继续扫描;否则,表达式不匹配。最后,如果栈为空,则表达式匹配;否则,表达式不匹配。
阅读全文