c语言栈算术表达式验算小括号是否配对
时间: 2023-12-02 18:40:23 浏览: 93
以下是C语言栈算术表达式验算小括号是否配对的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAXSIZE 100
typedef struct {
char data[MAXSIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
bool isEmpty(Stack *s) {
return s->top == -1;
}
bool isFull(Stack *s) {
return s->top == MAXSIZE - 1;
}
bool push(Stack *s, char c) {
if (isFull(s)) {
return false;
}
s->data[++s->top] = c;
return true;
}
bool pop(Stack *s, char *c) {
if (isEmpty(s)) {
return false;
}
*c = s->data[s->top--];
return true;
}
bool checkParentheses(char *exp) {
Stack s;
initStack(&s);
int len = strlen(exp);
for (int i = 0; i < len; i++) {
if (exp[i] == '(') {
push(&s, exp[i]);
} else if (exp[i] == ')') {
char c;
if (!pop(&s, &c) || c != '(') {
return false;
}
}
}
return isEmpty(&s);
}
int main() {
char exp[MAXSIZE];
printf("请输入一个算术表达式:");
scanf("%s", exp);
if (checkParentheses(exp)) {
printf("括号匹配\n");
} else {
printf("括号不匹配\n");
}
return 0;
}
```
阅读全文