本文主要是介绍利用顺序栈实现:判别表达式中括弧是否正确配对(BracketMatch函数),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include<stdio.h>
#include<stdlib.h>
#define INITSTACKSIZE 20
#define INCREASESIZE 10typedef char SElemType;
typedef struct {SElemType *base;SElemType *top;int stacksize;
} SqStack;void initStack(SqStack* S);//将S初始化空栈
void push(SqStack* S,SElemType e);//将e压入栈S
SElemType pop(SqStack* S);//弹栈S,返回弹出的元素
void showStack(SqStack* S);//查看栈所有数据
int isEmpty(SqStack* S);//判断栈是否为空
void createStack(SqStack* S,SElemType *arr,int n);//将长度为n的数组arr压入栈中char getLeft(char right);//获取传入括号右边的字符,返回左边的字符/*假设一个算数表达式中包含圆括弧、方括弧和花括弧三种类型的括弧,编写一个判别表达式中
括弧是否正确配对的BracketMatch函数。*/
int BracketMatch(SElemType *str);int main()
{SElemType *str = "{5+[4*(3+6)]-5}*6";printf("算术表达式:%s\n",str);if(BracketMatch(str)){printf("括弧正确匹配!");}else{printf("括弧不匹配!");}getchar();return 0;
}int BracketMatch(SElemType *str)
{SqStack S;SElemType *p = str;initStack(&S);while(*p != '\0'){if(*p == '(' || *p == '[' || *p == '{'){push(&S, *p);}if(*p == ')' || *p == ']' || *p == '}'){if(getLeft(*p) != pop(&S)){return 0;}}p++;}//若此时栈S为空,说明括号匹配return isEmpty(&S)?1:0;
}char getLeft(char right)
{switch(right){case ')':return '(';break;case ']':return '[';break;case '}':return '{';break;default:printf("getLeft() 函数参数不正确!");return 0;}
}void initStack(SqStack* S)
{S->base = (SElemType *)malloc(INITSTACKSIZE * sizeof(SElemType));if(NULL == S->base){printf("初始化栈失败!\n");exit(1);}S->top = S->base;S->stacksize = 0;
}int isEmpty(SqStack* S)
{if(S->stacksize == 0){return 1;}else{return 0;}
}void push(SqStack* S,SElemType e)
{if(S->stacksize <= S->top - S->base){S->base = (SElemType *)realloc(S->base,(S->stacksize + INCREASESIZE) * sizeof(SElemType));}*(S->top) = e;S->top++;S->stacksize++;
}SElemType pop(SqStack* S)
{if(S->base == S->top){printf("当前栈为空,不能进行弹栈操作!\n");return 0;}S->top--;S->stacksize--;return *(S->top);
}void showStack(SqStack* S)
{int i,length = S->top - S->base;for(i = 0;i < length;i++){printf("%c ",S->base[i]);}printf("\n");
}void createStack(SqStack* S,SElemType *arr,int n)
{int i;for(i = 0;i < n;i++){push(S,arr[i]);}
}
这篇关于利用顺序栈实现:判别表达式中括弧是否正确配对(BracketMatch函数)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!