中綴轉換為后綴:順序建立,如果不是運算符,直接輸出。如果是括號的話,先入左括號,然后等到右括號的時候,將這一段全部輸出。然后再就是運算優先級的問題了,每一次插入,都需要保證要插入的運算符小於棧頂的運算符。
中綴轉化為前綴:通過兩個棧實現,逆序建立,如果當前是字符的話,先放入第一個棧里面。入股如果是括號,將這兩個括號里面的棧2的放入棧1里面。然后再就是運算符優先級的問題了,當當前的字符是加或者減的時候,棧2的頂大於等於當前的運算符的時候停止。然后將棧2里面得棧頂放入棧1中,當前的字符加入棧2.最后將棧2里面的字符全部放入棧1.
AC代碼:
1 #include<bits/stdc++.h> 2 using namespace std; 3 # define ll long long 4 # define inf 0x3f3f3f3f 5 const int maxn = 2e5+100; 6 char Stack[maxn]; 7 char z1[maxn],z2[maxn]; 8 int top; 9 string str,str1,str2,str3; 10 int main() 11 { 12 cin>>str; 13 int len=str.size(); 14 for(int i=0; str[i]!='#'; i++) 15 { 16 if(str[i]>='a'&&str[i]<='z') 17 str1+=str[i]; 18 else if(str[i]=='(') 19 { 20 Stack[++top]=str[i]; 21 } 22 else if(str[i]==')') 23 { 24 while(top&&Stack[top]!='(') 25 { 26 str1+=Stack[top]; 27 top--; 28 } 29 top--; 30 } 31 else if(str[i]=='+'||str[i]=='-') 32 { 33 while(top&&Stack[top]!='(') 34 { 35 str1+=Stack[top]; 36 top--; 37 } 38 Stack[++top]=str[i]; 39 } 40 else if(str[i]=='*'||str[i]=='/') 41 { 42 while(top&&Stack[top]!='('&&(Stack[top]=='*'||Stack[top]=='/')) 43 { 44 str1+=Stack[top]; 45 top--; 46 } 47 Stack[++top]=str[i]; 48 } 49 } 50 while(top) 51 { 52 str1+=Stack[top]; 53 top--; 54 } 55 int top1=0,top2=0; 56 for(int i=len-2; i>=0; i--) 57 { 58 if(str[i]>='a'&&str[i]<='z') 59 { 60 z1[++top1]=str[i]; 61 } 62 else if((str[i]=='+'||str[i]=='-')&&(z2[top2]=='*'||z2[top2]=='/')) 63 { 64 z1[++top1]=z2[top2]; 65 z2[top2]=str[i]; 66 } 67 else if(str[i]=='(') 68 { 69 while(z2[top2]!=')') 70 { 71 z1[++top1]=z2[top2--]; 72 } 73 top2--; 74 } 75 else 76 { 77 z2[++top2]=str[i]; 78 } 79 } 80 while(top2) 81 { 82 z1[++top1]=z2[top2--]; 83 } 84 while(top1) 85 { 86 str2+=z1[top1]; 87 top1--; 88 } 89 for(int i=0; str[i]!='#'; i++) 90 { 91 if(str[i]=='('||str[i]==')') 92 continue; 93 str3+=str[i]; 94 } 95 cout<<str2<<endl<<str3<<endl<<str1<<endl; 96 }