假设表达式中允许包含圆括号、方括号和大括号3种括号,编写一个算法判断表达式中的括号是否正确配对。并将其用c语言实现,上机运行输出结果。用顺序栈实现。提示:输入一串包括左右圆、方、大括号的字符,则左括号
时间: 2023-04-19 20:01:30 浏览: 140
的入栈,右括号的出栈,若出栈的括号与当前右括号不匹配,则表达式不合法。最后判断栈是否为空,若为空则表达式合法,否则不合法。
以下是c语言实现的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
if (s->top == MAXSIZE - 1) {
printf("Stack overflow!\n");
exit(1);
}
s->data[++s->top] = c;
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Stack underflow!\n");
exit(1);
}
return s->data[s->top--];
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isMatch(char left, char right) {
if (left == '(' && right == ')') return 1;
if (left == '[' && right == ']') return 1;
if (left == '{' && right == '}') return 1;
return ;
}
int checkExpression(char *exp) {
Stack s;
initStack(&s);
int i = ;
while (exp[i] != '\') {
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') {
push(&s, exp[i]);
} else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') {
if (isEmpty(&s)) {
return ;
}
char left = pop(&s);
if (!isMatch(left, exp[i])) {
return ;
}
}
i++;
}
return isEmpty(&s);
}
int main() {
char exp[MAXSIZE];
printf("请输入表达式:");
scanf("%s", exp);
if (checkExpression(exp)) {
printf("表达式合法!\n");
} else {
printf("表达式不合法!\n");
}
return ;
}
阅读全文