试写一个判别表达式中开、闭括号是否配对出现的算法
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
// 栈结构定义
typedef struct {
char *array;
int top;
int capacity;
} Stack;
// 初始化栈
void initStack(Stack *s, int capacity) {
s->array = (char *)malloc(capacity * sizeof(char));
if (!s->array) {
fprintf(stderr, "Memory allocation failed\n");
exit(EXIT_FAILURE);
}
s->top = -1;
s->capacity = capacity;
}
// 检查栈是否为空
bool isEmpty(Stack *s) {
return s->top == -1;
}
// 入栈操作
void push(Stack *s, char item) {
if (s->top + 1 >= s->capacity) {
fprintf(stderr, "Stack overflow\n");
exit(EXIT_FAILURE);
}
s->array[++s->top] = item;
}
// 出栈操作
char pop(Stack *s) {
if (isEmpty(s)) {
fprintf(stderr, "Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->array[s->top--];
}
// 检查括号是否配对的函数
bool areParenthesesBalanced(const char *expression) {
Stack s;
int capacity = 100; // 假设输入不会太长
initStack(&s, capacity);
for (int i = 0; expression[i] != '\0'; i++) {
if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{') {
push(&s, expression[i]);
} else if (expression[i] == ')' || expression[i] == ']' || expression[i] == '}') {
if (isEmpty(&s)) {
// 没有匹配的左括号
free(s.array);
return false;
}
char topChar = pop(&s);
if ((expression[i] == ')' && topChar != '(') ||
(expression[i] == ']' && topChar != '[') ||
(expression[i] == '}' && topChar != '{')) {
// 括号不匹配
free(s.array);
return false;
}
}
}
// 检查栈是否为空,如果为空说明所有括号都匹配成功
bool result = isEmpty(&s);
free(s.array);
return result;
}
int main() {
char expression[101]; // 假设用户输入的最大长度为100个字符
printf("Enter an expression to check for balanced parentheses: ");
if (fgets(expression, sizeof(expression), stdin) == NULL) {
fprintf(stderr, "Failed to read input\n");
return EXIT_FAILURE;
}
// 去除fgets可能读取的换行符
expression[strcspn(expression, "\n")] = 0;
if (areParenthesesBalanced(expression)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}
return 0;
}