设表达式中允许包含3种括号:圆括号、方括号和大括号。即小括号、中括号和大 括号。编写一个算法来判断表达式中的括号是否正确配对,要求利用栈的结构实现。若匹配,输出yes.若不匹配,输出no。语言选DEV C++
时间: 2024-02-22 22:55:40 浏览: 130
好的,以下是实现代码:
```cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct Stack {
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");
exit(1);
}
s->data[++(s->top)] = c;
}
char pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty");
exit(1);
}
return s->data[(s->top)--];
}
int is_match(char left, char right) {
return (left == '(' && right == ')') ||
(left == '[' && right == ']') ||
(left == '{' && right == '}');
}
int is_balanced(char *exp) {
Stack s;
init(&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 (is_empty(&s)) {
return 0;
}
char left = pop(&s);
if (!is_match(left, exp[i])) {
return 0;
}
}
}
return is_empty(&s);
}
int main() {
char exp[MAX_SIZE];
printf("Enter expression: ");
gets(exp);
if (is_balanced(exp)) {
printf("yes");
} else {
printf("no");
}
return 0;
}
```
运行结果:
```
Enter expression: (a+b)*[c-d]/{e+f}
yes
```
```
Enter expression: (a+b)*[c-d/{e+f}
no
```
阅读全文