Advertisement
Adrita

task 7( ds lab 4) 3rd sem

Feb 3rd, 2020
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int prec(char c)
  4. {
  5. if(c=='^')
  6. return 5;
  7. else if(c == '/')
  8. return 4;
  9. else if(c == '*')
  10. return 3;
  11. else if(c == '-')
  12. return 2;
  13. else if(c == '+')
  14. return 1;
  15. else
  16. return -1;
  17. }
  18.  
  19. void infixToPostfix(string s)
  20. {
  21. stack<char> st;
  22. int l = s.length();
  23. string ns;
  24. for(int i = 0; i < l; i++)
  25. {
  26.  
  27. if((s[i] >= 'a' && s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z'))
  28. ns+=s[i];
  29. else if(s[i]=='('||s[i]=='{'||s[i]=='[')
  30. st.push(s[i]);
  31. else if(s[i]==')'||s[i]=='}'||s[i]==']')
  32. {
  33. while(!st.empty()&&((s[i]==')'&&st.top()!='(')||(s[i]=='}'&&st.top()!='{')||(s[i]==']'&&st.top()!='[')))
  34. {
  35. ns+=st.top();
  36. st.pop();
  37. }
  38. st.pop();
  39. }
  40.  
  41. else
  42. {
  43. while(!st.empty() && prec(s[i]) <= prec(st.top()))
  44. {
  45. char c = st.top();
  46. st.pop();
  47. ns += c;
  48. }
  49. st.push(s[i]);
  50. }
  51.  
  52. }
  53. while(!st.empty())
  54. {
  55. char c = st.top();
  56. st.pop();
  57. ns += c;
  58. }
  59.  
  60. cout << ns << endl;
  61.  
  62. }
  63.  
  64. int main()
  65. {
  66. int t;
  67. cin>>t;
  68. for(int i=0; i<t; i++)
  69. {
  70. string exp;
  71. cin>>exp;
  72. infixToPostfix(exp);
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement