資料結構-棧的應用-算術表示式小括號匹配
阿新 • • 發佈:2019-01-03
資料結構高分筆記,第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"); }