设一个算术表达式中包含圆括号、方括号和花括号三种类型的括号,编写一个算法判断其中的括号是否匹配用c语言编写全部代码
时间: 2024-03-05 12:53:32 浏览: 27
好的,以下是一个用C语言编写的算法,可以判断一个算术表达式中的括号是否匹配:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack* s) {
s->top = -1;
}
void push(Stack* s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Stack overflow\n");
exit(1);
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack* s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(1);
}
char c = s->data[s->top];
s->top--;
return c;
}
int isEmpty(Stack* s) {
return s->top == -1;
}
int isMatched(char left, char right) {
return (left == '(' && right == ')') || (left == '[' && right == ']') || (left == '{' && right == '}');
}
int isBalanced(char* exp) {
Stack s;
initStack(&s);
int i;
for (i = 0; exp[i] != '\0'; i++) {
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') {
push(&s, exp[i]);
} else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') {
if (isEmpty(&s) || !isMatched(pop(&s), exp[i])) {
return 0;
}
}
}
return isEmpty(&s);
}
int main() {
char exp[MAX_SIZE];
printf("Enter an arithmetic expression: ");
fgets(exp, MAX_SIZE, stdin);
exp[strlen(exp) - 1] = '\0'; // remove the newline character
if (isBalanced(exp)) {
printf("The expression is balanced\n");
} else {
printf("The expression is not balanced\n");
}
return 0;
}
```
该算法使用了一个栈来保存左括号,并在遇到右括号时判断是否与栈顶的左括号匹配。如果匹配,则弹出栈顶元素;否则,表达式中的括号不匹配。如果遍历完成后栈为空,则表达式中的括号匹配;否则,表达式中的括号不匹配。
希望这个算法可以帮助到您!