Adrita

infix to postfix using stack

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