fork download
  1. #include<bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int prec(char c){
  6. switch(c){
  7. case'^':
  8. return 3;
  9. case'/':
  10. case'*':
  11. return 2;
  12. case'+':
  13. case'-':
  14. return 1;
  15. default:
  16. return 0;
  17. }
  18. }
  19. void infixtoprefix(char infix[]){
  20. stack <char> s;
  21. int n = strlen(infix);
  22. int i;
  23. string out;
  24. for(i=0;i<n;i++){
  25. if((infix[i] >= 'a' && infix[i] <= 'z')||(infix[i] >= 'A' && infix[i] <= 'Z')){
  26. out += infix[i];
  27. }
  28. else if(infix[i] == '('){
  29. s.push('(');
  30. }
  31. else if(infix[i] == ')'){
  32. while(!s.empty() && s.top() != '('){
  33. s.pop();
  34. out += s.top();
  35. }
  36. }
  37. else{
  38. while(!s.empty() && prec(infix[i])<=prec(s.top())){
  39. s.pop();
  40. out += s.top();
  41. }
  42. s.push(infix[i]);
  43. }
  44. }
  45. while(s.top() != 'N'){
  46. s.pop();
  47. out += s.top();
  48. }
  49. cout << out << endl;
  50. }
  51. int main(){
  52. char infix[200];
  53. int t;
  54. cin >> t;
  55. while(t--){
  56. cin >> infix;
  57. infixtoprefix(infix);
  58. }
  59. return 0;
  60. }
  61.  
Success #stdin #stdout 0s 16072KB
stdin
Standard input is empty
stdout
Standard output is empty