用栈来解决括号匹配问题(C语言)代码
时间: 2023-06-02 08:08:14 浏览: 112
C实现的括号匹配问题,主要由栈实现
好的,以下是用栈来解决括号匹配问题的C语言代码:
```
#include<stdio.h>
#include<stdlib.h>
#define MAX_SIZE 100
typedef struct{
int top;
char data[MAX_SIZE];
}Stack;
void initStack(Stack* s){
s->top = -1;
}
void push(Stack* s, char c){
if(s->top == MAX_SIZE-1){
printf("Stack is full.\n");
return;
}
s->top++;
s->data[s->top] = c;
}
char pop(Stack* s){
if(s->top == -1){
printf("Stack is empty.\n");
return '\0';
}
char c = s->data[s->top];
s->top--;
return c;
}
int isMatch(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 isBalanced(char* exp){
Stack s;
initStack(&s);
int i = 0;
while(exp[i] != '\0'){
if(exp[i] == '(' || exp[i] == '[' || exp[i] == '{'){
push(&s, exp[i]);
}
else if(exp[i] == ')' || exp[i] == ']' || exp[i] == '}'){
if(s.top == -1 || !isMatch(pop(&s), exp[i])){
return 0;
}
}
i++;
}
return s.top == -1;
}
int main(){
char exp[MAX_SIZE];
printf("Enter the expression: ");
scanf("%s", exp);
if(isBalanced(exp)){
printf("The expression is balanced.\n");
}
else{
printf("The expression is not balanced.\n");
}
return 0;
}
```
以上代码可以判断输入的表达式是否符合括号匹配规则,如果匹配,则输出"the expression is balanced",否则输出"the expression is not balanced"。
阅读全文