c语言数据结构括号匹配的检验代码
时间: 2023-05-26 12:05:53 浏览: 128
数据结构中的括号匹配问题通常使用栈来解决
以下是一个简单的C语言代码,用于检验括号匹配:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 1000
typedef struct {
char data[MAX_SIZE];
int top;
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, char c) {
if (s->top == MAX_SIZE - 1) {
printf("Error: stack overflow!\n");
exit(1);
} else {
s->data[++(s->top)] = c;
}
}
char pop(Stack *s) {
if (s->top == -1) {
printf("Error: stack underflow!\n");
exit(1);
} else {
return s->data[(s->top)--];
}
}
int is_empty(Stack *s) {
return (s->top == -1);
}
char peek(Stack *s) {
if (s->top == -1) {
printf("Error: stack underflow!\n");
exit(1);
} else {
return s->data[s->top];
}
}
int is_matching_pair(char left, char right) {
if (left == '(' && right == ')') {
return 1;
} else if (left == '{' && right == '}') {
return 1;
} else if (left == '[' && right == ']') {
return 1;
} else {
return 0;
}
}
int check_matching_parenthesis(char *exp) {
Stack s;
init(&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 (is_empty(&s) || !is_matching_pair(peek(&s), exp[i])) {
return 0;
} else {
pop(&s);
}
}
}
return (is_empty(&s) ? 1 : 0);
}
int main() {
char exp[MAX_SIZE];
printf("Enter an expression: ");
scanf("%s", exp);
if (check_matching_parenthesis(exp)) {
printf("Expression is balanced.\n");
} else {
printf("Expression is not balanced.\n");
}
return 0;
}
```
该代码使用一个栈来存储左括号。当遇到左括号时,将其推入栈中。当遇到右括号时,检查栈是否为空,并且检查右括号是否与栈顶元素的左括号匹配。如果匹配,则将栈顶元素弹出,继续处理下一个字符。如果不匹配,则表达式不平衡。最后,如果栈为空,则表达式平衡,否则表达式不平衡。
阅读全文