Advertisement
Cinestra

Starting over Homework 2 Problem 5 a third time

Mar 29th, 2023
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.20 KB | None | 0 0
  1. bool infix_to_postfix(string infix, string& postfix)
  2. // Returns false if conversion fails
  3. {
  4. stack<char> stack_for_nonletters;
  5.  
  6. postfix = "";
  7.  
  8. for (int string_place = 0; string_place < infix.size(); string_place++)
  9. {
  10. char char_in_string = infix[string_place];
  11.  
  12. // If it's simply a letter, add to the postfix expression
  13. if (char_in_string >= 'a' && char_in_string <= 'z')
  14. {
  15. // If there was two letters in a row in the infix form, we will return false
  16. if (string_place > 0 && (infix[string_place - 1] >= 'a' && infix[string_place - 1] <= 'z'))
  17. return false;
  18.  
  19. if (string_place > 0 && infix[string_place - 1] )
  20.  
  21. postfix += char_in_string;
  22. }
  23.  
  24. // If there is an open brack, push it on the stack
  25. else if (char_in_string == '(')
  26. {
  27. stack_for_nonletters.push(char_in_string);
  28. }
  29.  
  30. // If it is a closed bracket, keep popping from the stack until a closing pair open bracket is found
  31. else if (char_in_string == ')')
  32. {
  33. while (stack_for_nonletters.top() != '(')
  34. {
  35. postfix += stack_for_nonletters.top();
  36. stack_for_nonletters.pop();
  37. }
  38.  
  39. // Now pop the open bracket
  40. stack_for_nonletters.pop();
  41. }
  42.  
  43. // Let's now take into account the operatators
  44. else
  45. {
  46. // If the stack isn't empty and the current character in the string is of lower priority than one about to be added
  47. // We will pop the stack until an operand of lower priority
  48. while (!stack_for_nonletters.empty() && priority(char_in_string) <= priority(stack_for_nonletters.top()))
  49. {
  50. postfix += stack_for_nonletters.top();
  51. stack_for_nonletters.pop();
  52. }
  53.  
  54. stack_for_nonletters.push(char_in_string);
  55. }
  56. }
  57.  
  58. // If we have finished going through the infix expression,
  59. while (!stack_for_nonletters.empty())
  60. {
  61. postfix += stack_for_nonletters.top();
  62. stack_for_nonletters.pop();
  63. }
  64.  
  65. return true;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement