利用栈用c语言定义一个函数用来判断算术表达式中包含圆括号、方括号是否正确配对。其中,括号配对共有四种情况:左右括号配对次序不正确:右括号多于左括号:左括号多于右括号:左右括号匹配正确
时间: 2024-06-04 15:11:07 浏览: 81
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MaxSize 100
typedef struct stack{
char data[MaxSize];
int top;
}stack;
//初始化栈
void InitStack(stack *s){
s->top = -1;
}
//入栈操作
bool Push(stack *s, char x){
if(s->top == MaxSize - 1){
return false;
}
s->data[++s->top] = x;
return true;
}
//出栈操作
bool Pop(stack *s, char *x){
if(s->top == -1){
return false;
}
*x = s->data[s->top--];
return true;
}
//判断栈是否为空
bool IsEmpty(stack *s){
return s->top == -1;
}
//判断栈是否已满
bool IsFull(stack *s){
return s->top == MaxSize - 1;
}
//获取栈顶元素
bool GetTop(stack *s, char *x){
if(s->top == -1){
return false;
}
*x = s->data[s->top];
return true;
}
//判断左右括号是否匹配
bool IsMatch(char left, char right){
if(left == '(' && right == ')'){
return true;
}
if(left == '[' && right == ']'){
return true;
}
return false;
}
//判断算术表达式中的括号是否配对
bool CheckBrackets(char *str){
stack s;
InitStack(&s);
int len = strlen(str);
for(int i = 0; i < len; i++){
if(str[i] == '(' || str[i] == '['){
Push(&s, str[i]);
}
else if(str[i] == ')' || str[i] == ']'){
char top;
if(GetTop(&s, &top) && IsMatch(top, str[i])){
Pop(&s, &top);
}
else{
return false;
}
}
}
return IsEmpty(&s);
}
int main(){
char str[MaxSize];
printf("请输入算术表达式:");
scanf("%s", str);
if(CheckBrackets(str)){
printf("左右括号匹配正确\n");
}
else{
printf("左右括号匹配不正确\n");
}
return 0;
}
阅读全文