|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 beannaeb 于 2020-10-31 18:36 编辑
- #include<stdio.h>
- #include<stdlib.h>
- #define MaxSize 100
- typedef char ElemType;
- typedef struct
- { ElemType data[MaxSize];
- int top;
- }SqStack;
-
- //初始化栈运算算法
- void InitStack(SqStack &st)
- {
- st.top=-1;
- }
-
- //销毁栈运算算法
- void DestroyStack(SqStack st)
- {
- }
-
- //进栈运算算法
- int Push(SqStack &st,ElemType x)
- { if(st.top==MaxSize-1) //栈满上溢出返回0
- return 0;
- else
- { st.top++;
- st.data[st.top]=x;
- return 1; //成功进栈返回1
- }
- }
- //出栈运算算法
- int Pop(SqStack &st,ElemType &x) //x为引用型参数
- { if(st.top==-1) //栈空返回0
- return 0;
- else
- { x=st.data[st.top];
- st.top--; //成功出栈返回1
- return 1;
- }
- }
-
- //取栈顶元素运算算法
- int GetTop(SqStack st,ElemType &x) //x为引用型参数
- { if(st.top==-1) //栈空返回0
- return 0;
- else
- { x=st.data[st.top];
- return 1; //成功取栈项返回1
- }
- }
-
- //判断栈空运算算法
- int StackEmpty(SqStack st)
- { if(st.top==-1)return 1; //栈空返回1
- else return 0; //栈不空返回0
- }
- int Match(char exp[],int n)
- {
- SqStack st;
- InitStack(st);
- int flag=1,i=0;
- char ch;
- while(i<n&&flag==1)
- {
- switch(exp[i])
- {
- case'(':case'[':case'{':
- Push(st,exp[i]);break;
- case')':
- if(!Pop(st,ch)||ch!='(')
- flag=0;
- break;
- case']':
- if(!Pop(st,ch)||ch!='[')
- flag=0;
- break;
- case'}':
- if(!Pop(st,ch)||ch!='{')
- flag=0;
- break;
- }
- i++;
- }
- if(StackEmpty(st)&&flag==1)
- {
- DestroyStack(st);
- return 1;
- }
- else
- {
- DestroyStack(st);
- return 0;
- }
- }
- int main()
- {
- SqStack st;
- int n;
- int flag;
- char *exp;
- printf("判断结果如下\n");
- flag=Match(exp,n);
- printf("[(])%s\n",(flag==1?"是匹配的表达式":"不是匹配的表达式"));
- printf("[()]%s\n",(flag==1?"是匹配的表达式":"不是匹配的表达式"));
- printf("[()])%s\n",(flag ==1?"是匹配的表达式":"不是匹配的表达式"));
- printf("([()]%s\n",(flag==1?"是匹配的表达式":"不是匹配的表达式"));
- }
复制代码
本帖最后由 巴巴鲁 于 2020-10-31 21:06 编辑
很离谱,主函数里n和exp没有初始化或赋值,就当参数传进去了
关于括号匹配,我自己刚刚写了一个代码,仅供参考:
|
|