Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- bool infix_to_postfix(string infix, string& postfix)
- // Returns false if conversion fails
- {
- stack<char> stack_for_nonletters;
- postfix = "";
- for (int string_place = 0; string_place < infix.size(); string_place++)
- {
- char char_in_string = infix[string_place];
- // If it's simply a letter, add to the postfix expression
- if (char_in_string >= 'a' && char_in_string <= 'z')
- {
- // If there was two letters in a row in the infix form, we will return false
- if (string_place > 0 && (infix[string_place - 1] >= 'a' && infix[string_place - 1] <= 'z'))
- return false;
- if (string_place > 0 && infix[string_place - 1] )
- postfix += char_in_string;
- }
- // If there is an open brack, push it on the stack
- else if (char_in_string == '(')
- {
- stack_for_nonletters.push(char_in_string);
- }
- // If it is a closed bracket, keep popping from the stack until a closing pair open bracket is found
- else if (char_in_string == ')')
- {
- while (stack_for_nonletters.top() != '(')
- {
- postfix += stack_for_nonletters.top();
- stack_for_nonletters.pop();
- }
- // Now pop the open bracket
- stack_for_nonletters.pop();
- }
- // Let's now take into account the operatators
- else
- {
- // If the stack isn't empty and the current character in the string is of lower priority than one about to be added
- // We will pop the stack until an operand of lower priority
- while (!stack_for_nonletters.empty() && priority(char_in_string) <= priority(stack_for_nonletters.top()))
- {
- postfix += stack_for_nonletters.top();
- stack_for_nonletters.pop();
- }
- stack_for_nonletters.push(char_in_string);
- }
- }
- // If we have finished going through the infix expression,
- while (!stack_for_nonletters.empty())
- {
- postfix += stack_for_nonletters.top();
- stack_for_nonletters.pop();
- }
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement