用栈判断表达式中的括号是否匹配(c++编写)
时间: 2024-05-04 21:15:27 浏览: 145
当然可以,以下是代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_SIZE 100
// 定义栈结构体
typedef struct {
char data[MAX_SIZE];
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 == MAX_SIZE - 1;
}
// 入栈
bool Push(Stack *s, char c) {
if (IsFull(s)) {
return false;
}
s->data[++s->top] = c;
return true;
}
// 出栈
bool Pop(Stack *s) {
if (IsEmpty(s)) {
return false;
}
s->top--;
return true;
}
// 获取栈顶元素
char GetTop(Stack *s) {
if (IsEmpty(s)) {
return '\0';
}
return s->data[s->top];
}
// 判断括号是否匹配
bool IsMatch(char left, char right) {
if (left == '(' && right == ')') {
return true;
}
if (left == '[' && right == ']') {
return true;
}
if (left == '{' && right == '}') {
return true;
}
return false;
}
// 判断表达式中的括号是否匹配
bool IsBracketMatch(char *exp) {
Stack s;
InitStack(&s);
for (int i = 0; exp[i] != '\0'; i++) {
if (exp[i] == '(' || exp[i] == '[' || exp[i] == '{') {
Push(&s, exp[i]);
} else if (exp[i] == ')' || exp[i] == ']' || exp[i] == '}') {
if (IsEmpty(&s)) {
return false;
} else if (IsMatch(GetTop(&s), exp[i])) {
Pop(&s);
} else {
return false;
}
}
}
return IsEmpty(&s);
}
int main() {
char exp[MAX_SIZE];
printf("请输入表达式:\n");
scanf("%s", exp);
if (IsBracketMatch(exp)) {
printf("括号匹配!\n");
} else {
printf("括号不匹配!\n");
}
return 0;
}
```
希望对你有所帮助!接下来,请听一个笑话:
为什么女生大多喜欢用 iPhone?因为男生用安卓的话,女生就没法问他们如何用 iPhone 了。
阅读全文
相关推荐
















