[关闭]
@geek-sjl 2018-10-31T09:12:23.000000Z 字数 1663 阅读 489

18图灵班作业13:中缀式转换为逆波兰表达式

代码实现:

  1. #include <vector>
  2. #include <stack>
  3. #include <iostream>
  4. #include <map>
  5. using namespace std;
  6. stack<int> t1;
  7. stack<char> t2;
  8. map<char,int> priority;
  9. int toInt(string goal){
  10. int ans=0;
  11. for(int i=0;i<goal.size();i++){
  12. ans*=10;
  13. ans+=goal[i]-'0';
  14. }
  15. return ans;
  16. }
  17. void initPriority(){
  18. priority['+']=1;
  19. priority['-']=1;
  20. priority['*']=2;
  21. priority['/']=2;
  22. priority['(']=0;
  23. priority[')']=0;
  24. }
  25. int main(){
  26. freopen("test.in","r",stdin);
  27. freopen("test.out","w",stdout);
  28. initPriority();
  29. string now;
  30. while(cin>>now){
  31. if(now=="*"||now=="/"||now=="+"||now=="-"||now=="("||now==")"){
  32. if(now=="("||t2.empty()){
  33. t2.push(now[0]);
  34. continue;
  35. }
  36. if(now==")"){
  37. while(t2.top()!='('){
  38. char tmp=t2.top();
  39. t2.pop();
  40. cout<<tmp<<" ";
  41. }
  42. t2.pop();
  43. continue;
  44. }
  45. char nowTop=t2.top();
  46. if(priority[nowTop]<priority[now[0]]){
  47. t2.push(now[0]);
  48. }
  49. else{
  50. while(!t2.empty()&&priority[t2.top()]!=0&&priority[t2.top()]>=priority[now[0]]){
  51. char tmp=t2.top();
  52. t2.pop();
  53. cout<<tmp;
  54. }
  55. t2.push(now[0]);
  56. }
  57. // if(now=="*"||now=="/"&&(t2.top()!='*'||t2.top()!='/')){
  58. // t2.push(now[0]);
  59. // }
  60. // if(now=="+"||now=="-"){
  61. // while(!t2.empty()&&(t2.top()=='*'||t2.top()=='/'||t2.top()=='+'||t2.top()=='-')){
  62. // char tmp=t2.top();
  63. // t2.pop();
  64. // cout<<tmp;
  65. // }
  66. // t2.push(now[0]);
  67. // }
  68. }
  69. else{
  70. int tmp=toInt(now);
  71. cout<<tmp<<" ";
  72. }
  73. }
  74. while(!t2.empty()){
  75. char tmp=t2.top();
  76. t2.pop();
  77. cout<<tmp<<" ";
  78. }
  79. }

思路

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注