實驗3-棧和佇列——表示式求值(2132)
阿新 • • 發佈:2019-02-16
資料結構實驗之棧與佇列二:一般算術表示式轉換成字尾式
Time Limit: 1000MS Memory Limit: 65536KBProblem Description
對於一個基於二元運算子的算術表示式,轉換為對應的字尾式,並輸出之。
Input
輸入一個算術表示式,以‘#’字元作為結束標誌。
Output
輸出該表示式轉換所得到的字尾式。
Example Input
a*b+(c-d/e)*f#
Example Output
ab*cde/-f*+
程式碼:
#include<iostream> #include<stack> using namespace std; stack<char> s; int compare(char a,char b) { if(b=='@') return 0; if( (a=='*'||a=='/')&&(b=='+'||b=='-') || (b=='(') ) return 1; else return -1; } int main() { char c; s.push('@'); while(cin>>c&&c!='#') { if(c>='a'&&c<='z') cout<<c; else if(c=='(') { s.push('('); } else if(c==')') { while(s.top()!='(') { cout<<s.top(); s.pop(); } s.pop(); } else { if(compare(c,s.top())==1) s.push(c); else if(compare(c,s.top())==-1) { cout<<s.top(); s.pop(); s.push(c); } else { s.pop(); s.push(c); } } } while(!s.empty()) { cout<<s.top(); s.pop(); } return 0; }