数据结构高分笔记,第3章《栈》的第一个例题,题目要求检测算术表达式中小括号匹配是否合法。感觉自己的算法还是有点弱智啊,这么多判断好像很low逼!!!!
#include <stdio.h>
#include <string.h>
#define max 5
typedef struct
{
char exp[max];
int top;
}sqstack;
void main()
{
sqstack st;
int i=0;
int counter1=0;
st.top=-1;
char *s ="(sa(s(d))f)(";//测试数据入口
printf("\n");
while (*s!=NULL)
{
if ( *s==')'&&st.exp[st.top]!='(' )//右括号前无左括号,匹配失败,提示
{
st.top++;
st.exp[st.top]=*s;
break;
}
if ( *s==')'&&st.exp[st.top]=='(' )//与前一个左括号匹配成功,出栈
{
st.exp[st.top]='0';
st.top--;
*++s;
continue;
}
if ( *s=='(' )//左括号为起始括号,始终可以入栈
{
st.top++;
st.exp[st.top]=*s;
*++s;
continue;
}
if ( *s!='('&&*s!=')' )//跳过普通字符
{
*++s;
}
}
if ( st.exp[st.top]=='('||st.exp[st.top]==')' )
{
printf("error\n");
}
else printf("no error\n");
}