Sreekar_0125

Untitled

Sep 13th, 2022
190
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.34 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<algorithm>
  4. #include<cctype>
  5. using namespace std;
  6. char stack[100000];
  7. int top=-1;
  8. void push(char ch) {
  9.     top++;
  10.     stack[top]=ch;
  11. }
  12. void pop () {
  13.     top--;
  14. }
  15. int priority(char ch) {
  16.     if(ch == '^') {return 3;}
  17.     else if(ch == '*' || ch == '/' || ch == '%') {return 2;}
  18.     else if(ch == '+' || ch == '-') {return 1;}
  19.     else {return -1;}
  20.    
  21. }
  22. int main () {
  23.     string s;
  24.     cin >> s;
  25.     reverse(s.begin(),s.end());
  26.     for(int i=0;i<s.length();i++) {
  27.         if(s[i]=='(') {
  28.             s[i]=')';
  29.         }
  30.         else if(s[i]==')') {
  31.             s[i]='(';
  32.         }
  33.     }
  34.    
  35.     string s1;
  36.     for(int i=0;i<s.length();i++) {
  37.         if(isalnum(s[i])) {
  38.             s1.push_back(s[i]);
  39.         }
  40.         else if(s[i]=='(') {
  41.             push(s[i]);
  42.         }
  43.         else if(s[i]==')') {
  44.             while(stack[top]!='(') {
  45.                 s1.push_back(stack[top]);
  46.                 pop();
  47.             }
  48.             top--;
  49.         }
  50.         else {
  51.             while(priority(s[i]) <= priority(stack[top])) {
  52.                 s1.push_back(stack[top]); pop();
  53.             }
  54.             push(s[i]);
  55.         }
  56.     }
  57.     for(int i=top;i>=0;i--) {
  58.         s1.push_back(stack[i]);
  59.     }
  60.     reverse(s1.begin(),s1.end());
  61.     cout << s1 << endl;
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment