Advertisement
hadiuzzaman65

uva 727 problem solution

Jul 3rd, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <string.h>
  3. #include <stack>
  4. using namespace std;
  5. bool isoperand(char s)
  6. {
  7.     if(s=='+'|| s=='-'|| s=='*'|| s=='/'||s=='^'||s=='('||s==')')
  8.         return false;
  9.     return true;
  10. }
  11. int precidence(char s)
  12. {
  13.     if(s==')')
  14.         return 1;
  15.     if(s=='+'|| s=='-')
  16.         return 2;
  17.     else if(s=='*'|| s=='/')
  18.         return 3;
  19.     else if (s=='^')
  20.         return 4;
  21.     else
  22.         return 0;
  23. }
  24. char *convertpost(char *infix)
  25. {
  26.     char *postfix;
  27.     stack<char>stk;
  28.     int len=strlen(infix);
  29.     postfix=new char[len+1];
  30.     int i=0,j=0;
  31.     char x;
  32.     while(infix[i] !='\0')
  33.     {
  34.         if(isoperand(infix[i]))
  35.         {
  36.             postfix[j++]=infix[i++];
  37.         }
  38.         else if(infix[i]=='(')
  39.         {
  40.             stk.push(infix[i]);
  41.             i++;
  42.  
  43.  
  44.         }
  45.         else if(infix[i]==')')
  46.         {
  47.             while(stk.top()!='(')
  48.             {
  49.                 postfix[j++]=stk.top();
  50.                 stk.pop();
  51.  
  52.             }
  53.             stk.pop();
  54.              i++;
  55.  
  56.  
  57.         }
  58.         else
  59.         {
  60.             while(precidence(stk.top())>=precidence(infix[i]))
  61.             {
  62.                 postfix[j++]=stk.top();
  63.                 stk.pop();
  64.  
  65.             }
  66.             stk.push(infix[i]);
  67.             i++;
  68.         }
  69.  
  70.     }
  71.     while(!stk.empty())
  72.     {
  73.         postfix[j++]=stk.top();
  74.         stk.pop();
  75.     }
  76.     postfix[j]='\0';
  77.     return postfix;
  78. }
  79. int main()
  80. {
  81.     int n;
  82.     cin>>n;
  83.     cin.ignore();
  84.     cout<<endl;
  85.     while(n--)
  86.     {
  87.         char s[50];
  88.         char ch[4];
  89.         int i=0;
  90.         while(1)
  91.         {
  92.             gets(ch);
  93.             int len=strlen(ch);
  94.             if(len==0)
  95.                 break;
  96.             s[i]=ch[0];
  97.             i++;
  98.         }
  99.         s[i]='\0';
  100.  
  101.         char *postfix=convertpost(s);
  102.         puts(postfix);
  103.         cout<<endl;
  104.     }
  105.     return 0;
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement