splash365

Infix2post (using linked list)

Jan 8th, 2021 (edited)
159
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1.  #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Stack
  6. {
  7.     char data;
  8.     Stack *next;
  9. };
  10.  
  11. Stack *top = NULL;
  12.  
  13. Stack *StackNode(char val)
  14. {
  15.     Stack *newNode = new Stack();
  16.     newNode->data = val;
  17.     newNode->next = NULL;
  18.     return newNode;
  19. }
  20.  
  21.  
  22. void push(char val)
  23. {
  24.     Stack *newNode = StackNode(val);
  25.     if(top == NULL) top = newNode;
  26.     else
  27.     {
  28.         newNode->next = top;
  29.         top = newNode;
  30.     }
  31. }
  32.  
  33. void pop()
  34. {
  35.     Stack *cur = top;
  36.     top = top->next;
  37.     free(cur);
  38. }
  39.  
  40. int precedence(char ch)
  41. {
  42.     if(ch=='+' || ch=='-') return 1;
  43.     else if(ch=='*' || ch=='/') return 2;
  44.     else if(ch=='^') return 3;
  45.     else return 0;
  46.  
  47. }
  48.  
  49. int main()
  50. {
  51.     string s;
  52.     cin>>s;
  53.  
  54.     string res = "";
  55.  
  56.     for(int  i=0 ; i<s.size(); i++)
  57.     {
  58.         if(s[i] == '(') push(s[i]);
  59.         else if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' || s[i]=='^')
  60.         {
  61.             if(top == NULL) push(s[i]);
  62.             else
  63.             {
  64.                 while(precedence(s[i]) <= precedence(top->data))
  65.                 {
  66.                     res += top->data;
  67.                     res += " ";
  68.                     pop();
  69.                     if(top==NULL)
  70.                         break;
  71.                 }
  72.                 push(s[i]);
  73.             }
  74.  
  75.         }
  76.         else if(s[i]==')')
  77.         {
  78.             while(top->data != '(')
  79.             {
  80.                 res += top->data;
  81.                 res += " ";
  82.                 pop();
  83.             }
  84.             pop();
  85.         }
  86.         else
  87.         {
  88.             res += s[i];
  89.             res += " ";
  90.         }
  91.     }
  92.  
  93.     while(top != NULL)
  94.     {
  95.         res += top->data;
  96.         res += " ";
  97.         pop();
  98.     }
  99.  
  100.     cout<<res<<endl;
  101. }
  102.  
  103.  
  104.  
  105. /*
  106. INPUT : (A+(((B*C)-((D/(E^F))*G))*H))
  107. OUTPUT: ABC*DEF^/G*-H*+
  108. */
  109.  
  110.  
  111.  
  112.  
Add Comment
Please, Sign In to add comment