栈和队列 表达式的翻版
(3+(4*5))-(6)类似于这样的例子,表达式的某些括号显然是多加的,现在的要求是,如何输出正确的表达式?
请各位大神帮忙看看
#include <iostream> #include <string> using namespace std; int FindNext(string s,int l) { int i,j=1; for (i=l+1; i<s.length(); i++) { if (s[i]=='(') j++; else if (s[i]==')') j--; if (j==0) return i; } } int Lowest(string s) { int i=0,j=-1; while (i<s.length()) { if (s[i]=='(') i=FindNext(s,i)+1; if (s[i]=='+' || s[i]=='-') j=i; else if ((s[i]=='*' || s[i]=='/') && (j==-1 || s[j]=='*' || s[i]=='/')) j=i; i++; } return j; } int Allnum(string s) { int i; for (i=0; i<s.length(); i++) if (s[i]<'0' || s[i]>'9') return 0; return 1; } string Cal(string s,char *ch) { int len=s.length(); if (Allnum(s)) { (*ch)=' '; return s; } if ((s[0]=='(') &&(FindNext(s,0)==len-1)) { string ss(s,1,len-2); return Cal(ss,ch); } int low=Lowest(s); *ch=s[low]; string Ls(s,0,low),Rs(s,low+1,len-low); char Lch,Rch; Ls=Cal(Ls,&Lch); Rs=Cal(Rs,&Rch); if (*ch=='+') return Ls+'+'+Rs; else if (*ch=='-') { if ((Rch=='+') || (Rch=='-')) return Ls+'-'+'('+Rs+')'; else return Ls+'-'+Rs; } else if (*ch=='*') { if ((Lch=='+') || (Lch=='-')) Ls='('+Ls+')'; if ((Rch=='+') || (Rch=='-')) Rs='('+Rs+')'; return Ls+'*'+Rs; } else if (*ch=='/') { if ((Lch=='+') || (Lch=='-')) Ls='('+Ls+')'; if (Rch!=' ') Rs='('+Rs+')'; return Ls+'/'+Rs; } } int main() { string s; char ch; cin>>s; cout<<Cal(s,&ch)<<endl; system("pause"); return 0; }
char op[]={ '+' , '-' , '*' , '/' , ')' }优先级递增