数据结构c语言括号匹配
时间: 2023-11-04 18:07:12 浏览: 177
数据结构中的括号匹配是指在一个字符串中,判断其中的括号是否匹配。在C语言中,可以使用栈来实现括号匹配。具体实现方法是,遍历字符串中的每一个字符,如果是左括号,则将其入栈;如果是右括号,则将栈顶元素出栈,并判断其是否与当前右括号匹配。如果匹配,则继续遍历字符串;如果不匹配,则说明括号不匹配,返回false。最后,如果栈为空,则说明括号匹配,返回true。
下面是一个简单的C语言括号匹配的代码实现:
```
#include <stdio.h>
#include <stdbool.h>
#define STACK_MAX_SIZE 100
typedef struct CharStack {
int top;
char data[STACK_MAX_SIZE];
} *CharStackPtr;
bool bracketMatching(char* expression, int length) {
CharStackPtr stack = (CharStackPtr)malloc(sizeof(struct CharStack));
stack->top = -1;
for (int i = 0; i < length; i++) {
if (expression[i] == '(' || expression[i] == '[' || expression[i] == '{') {
stack->data[++stack->top] = expression[i];
} else if (expression[i] == ')' || expression[i] == ']' || expression[i] == '}') {
if (stack->top == -1) {
return false;
}
char temp = stack->data[stack->top--];
if ((expression[i] == ')' && temp != '(') || (expression[i] == ']' && temp != '[') || (expression[i] == '}' && temp != '{')) {
return false;
}
}
}
if (stack->top != -1) {
return false;
}
return true;
}
int main() {
char* expression = "[2 + (1 - 3)] * 4";
bool match = bracketMatching(expression, 17);
printf("Is the expression '%s' bracket matching? %d \r\n", expression, match);
return 0;
}
```
阅读全文
相关推荐


















