数据结构C语言括号匹配代码
时间: 2024-02-18 08:57:29 浏览: 108
括号匹配 C语言代码
以下是一个使用栈来实现括号匹配的C语言代码示例:
```c
#include <stdio.h>
#include <stdbool.h>
#define STACK_MAX_SIZE 100
typedef struct CharStack {
int top;
char data[STACK_MAX_SIZE];
} CharStack;
void initStack(CharStack *stack) {
stack->top = -1;
}
bool isEmpty(CharStack *stack) {
return stack->top == -1;
}
bool isFull(CharStack *stack) {
return stack->top == STACK_MAX_SIZE - 1;
}
void push(CharStack *stack, char c) {
if (isFull(stack)) {
printf("Stack is full. Cannot push element.\n");
return;
}
stack->data[++stack->top] = c;
}
char pop(CharStack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty. Cannot pop element.\n");
return '\0';
}
return stack->data[stack->top--];
}
bool isMatchingPair(char opening, char closing) {
if (opening == '(' && closing == ')')
return true;
else if (opening == '{' && closing == '}')
return true;
else if (opening == '[' && closing == ']')
return true;
else
return false;
}
bool isBalanced(char expression[]) {
CharStack stack;
initStack(&stack);
for (int i = 0; expression[i] != '\0'; i++) {
if (expression[i] == '(' || expression[i] == '{' || expression[i] == '[') {
push(&stack, expression[i]);
} else if (expression[i] == ')' || expression[i] == '}' || expression[i] == ']') {
if (isEmpty(&stack) || !isMatchingPair(pop(&stack), expression[i])) {
return false;
}
}
}
return isEmpty(&stack);
}
int main() {
char expression[100];
printf("Enter an expression: ");
fgets(expression, sizeof(expression), stdin);
if (isBalanced(expression)) {
printf("The expression is balanced.\n");
} else {
printf("The expression is not balanced.\n");
}
return 0;
}
```
阅读全文