c语言判别算数表达式括号配对
时间: 2023-10-26 13:20:53 浏览: 81
以下是一个简单的C语言程序,用于判别算数表达式中括号是否配对:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char data;
int index;
} StackNode;
typedef struct {
int top;
int maxSize;
StackNode* stack;
} Stack;
Stack* createStack(int maxSize) {
Stack* stack = (Stack*)malloc(sizeof(Stack));
stack->top = -1;
stack->maxSize = maxSize;
stack->stack = (StackNode*)malloc(sizeof(StackNode) * maxSize);
return stack;
}
void destroyStack(Stack* stack) {
free(stack->stack);
free(stack);
}
void push(Stack* stack, char data, int index) {
if (stack->top >= stack->maxSize - 1) {
printf("Stack overflow\n");
return;
}
stack->top++;
stack->stack[stack->top].data = data;
stack->stack[stack->top].index = index;
}
StackNode* pop(Stack* stack) {
if (stack->top < 0) {
return NULL;
}
StackNode* node = &(stack->stack[stack->top]);
stack->top--;
return node;
}
int isPair(char left, char right) {
if (left == '(' && right == ')') {
return 1;
}
if (left == '[' && right == ']') {
return 1;
}
if (left == '{' && right == '}') {
return 1;
}
return 0;
}
void checkParentheses(char* expression) {
Stack* stack = createStack(strlen(expression));
for (int i = 0; i < strlen(expression); i++) {
if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{') {
push(stack, expression[i], i);
} else if (expression[i] == ')' || expression[i] == ']' || expression[i] == '}') {
StackNode* node = pop(stack);
if (node == NULL || !isPair(node->data, expression[i])) {
printf("Unmatched parentheses at index %d\n", i);
return;
}
}
}
if (stack->top >= 0) {
printf("Unmatched parentheses at index %d\n", stack->stack[stack->top].index);
} else {
printf("All parentheses are well matched\n");
}
destroyStack(stack);
}
int main() {
char expression[100];
printf("Enter an arithmetic expression: ");
scanf("%s", expression);
checkParentheses(expression);
return 0;
}
```
该程序使用了一个栈来存储左括号,当遇到右括号时,从栈中弹出一个左括号进行匹配。如果匹配成功,则继续扫描;否则,输出错误信息并结束程序。
需要注意的是,该程序只能判断括号是否配对,而不能判断算数表达式的其他语法错误。如果需要进行更复杂的语法分析,需要使用更高级的技术,如递归下降分析或LR分析等。
阅读全文