splash365

post2infix (linked list)

Jan 8th, 2021 (edited)
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.25 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. struct Stack
  6. {
  7.     string data;
  8.     Stack *next;
  9. };
  10.  
  11. Stack *top = NULL;
  12.  
  13. Stack *StackNode(string val)
  14. {
  15.     Stack *newNode = new Stack();
  16.     newNode->data = val;
  17.     newNode->next = NULL;
  18.     return newNode;
  19. }
  20.  
  21.  
  22. void push(string 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.  
  41. int main()
  42. {
  43.     string s;
  44.     cin>>s;
  45.  
  46.     string res = "";
  47.     for(int i=0; i<s.size(); i++)
  48.     {
  49.         if(s[i]=='+' || s[i]=='-' || s[i]=='*' || s[i]=='/' || s[i]=='^')
  50.         {
  51.             res = "";
  52.  
  53.             string s1 = top->data;
  54.             pop();
  55.             string s2 = top->data;
  56.             pop();
  57.  
  58.             res += "(";
  59.             res += s2;
  60.             res += s[i];
  61.             res += s1;
  62.             res += ")";
  63.  
  64.             push(res);
  65.         }
  66.         else
  67.         {
  68.             string temp = "";
  69.             temp += s[i];
  70.             push(temp);
  71.         }
  72.     }
  73.  
  74.     cout<<res<<endl;
  75.  
  76. }
  77.  
  78.  
  79. /*
  80. INPUT  : ABC*DEF^/G*-H*+
  81. OUTPUT : (A+(((B*C)-((D/(E^F))*G))*H))
  82. */
  83.  
  84.  
  85.  
Add Comment
Please, Sign In to add comment