Advertisement
Guest User

Untitled

a guest
Dec 5th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. #include <iostream>
  2. #include <fstream>
  3. #include <queue>
  4. #include <stack>
  5. #include <string.h>
  6. #include <string>
  7. using namespace std;
  8.  
  9. ifstream in("input.in");
  10. ifstream output("output.out");
  11.  
  12. queue<char> infix;
  13. queue<string> postfix;
  14.  
  15. void toPostFix();
  16. int priority(char c);
  17. bool isOperand(char c);
  18.  
  19. int main(){
  20.  
  21. char s[100001];
  22. in.getline(s, 100001);
  23.  
  24. for(int i = 0; i < strlen(s); i++){
  25. infix.push(s[i]);
  26. }
  27.  
  28. toPostFix();
  29.  
  30. bool b = false;
  31.  
  32. while(!postfix.empty()){
  33.  
  34.  
  35. cout<<postfix.front()<<" ";
  36.  
  37. postfix.pop();
  38. }
  39.  
  40. return 0;
  41. }
  42.  
  43. void toPostFix(){
  44.  
  45. stack<char> s;
  46.  
  47. while(!infix.empty()){
  48. char c = infix.front();
  49. infix.pop();
  50.  
  51. if(isOperand(c)){
  52.  
  53. int n = (c - '0');
  54.  
  55. while(isOperand(infix.front())){
  56. int ch = infix.front();
  57. n = n * 10 + (int)(ch - '0');
  58. infix.pop();
  59. }
  60.  
  61. string st = to_string(n);
  62. postfix.push( st );
  63. } else if(c == '('){
  64. s.push(c);
  65. } else if(c == ')') {
  66. while(s.top() != '('){
  67. string st(1, s.top());
  68.  
  69.  
  70. postfix.push( st );
  71. s.pop();
  72. }
  73. s.pop();
  74. } else {
  75. while( !s.empty() && priority(s.top()) >= priority(c) ){
  76. string st(1, s.top());
  77. postfix.push( st );
  78. s.pop();
  79. }
  80. s.push(c);
  81. }
  82.  
  83.  
  84. }
  85.  
  86. while(!s.empty()){
  87. string st(1, s.top());
  88. postfix.push( st );
  89. s.pop();
  90. }
  91.  
  92. }
  93.  
  94. bool isOperand(char c){
  95. if(strchr("+-*/^()", c) != NULL){
  96. return false;
  97. }
  98. return true;
  99. }
  100.  
  101. int priority(char c){
  102. if(c == '+' || c == '-')
  103. return 1;
  104. if(c == '*' || c == '/')
  105. return 2;
  106. if(c == '^')
  107. return 3;
  108. return -1;
  109. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement