c语言假设算术表达式中允许包含两种括号:圆括号和方括号,其嵌套的顺序随意,即([][]) 或[([]())]等为正确格式,而[(]或()))或 [())均为不正确的格式。请使用栈结构,写一算法检验某表达式中的括号是否匹配,并测试你的算法是否正确
时间: 2024-01-01 20:03:12 浏览: 36
算法思路:
1. 定义一个栈结构,用于存放左括号(即圆括号和方括号)。
2. 从左到右遍历表达式中的每一个字符,如果是左括号则入栈,如果是右括号则判断栈顶元素是否为对应的左括号,如果是则弹出栈顶元素,否则表达式不匹配。
3. 遍历完整个表达式后,如果栈为空,则表达式匹配,否则表达式不匹配。
代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
bool is_empty(Stack *s) {
return s->top == -1;
}
bool 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--];
}
char peek(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top];
}
bool is_match(char left, char right) {
return (left == '(' && right == ')') || (left == '[' && right == ']');
}
bool check_expression(char *exp) {
Stack s;
init(&s);
for (int i = 0; i < strlen(exp); i++) {
char c = exp[i];
if (c == '(' || c == '[') {
push(&s, c);
} else if (c == ')' || c == ']') {
if (is_empty(&s)) {
return false;
}
char left = pop(&s);
if (!is_match(left, c)) {
return false;
}
}
}
return is_empty(&s);
}
int main() {
char exp[100];
printf("Enter an expression: ");
scanf("%s", exp);
if (check_expression(exp)) {
printf("The expression is well-formed.\n");
} else {
printf("The expression is not well-formed.\n");
}
return 0;
}
```
测试:
输入样例1:
```
[()()]
```
输出样例1:
```
The expression is well-formed.
```
输入样例2:
```
[(])
```
输出样例2:
```
The expression is not well-formed.
```