Skip to content

Instantly share code, notes, and snippets.

@Shadows-of-Fire
Created September 28, 2019 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Shadows-of-Fire/312c18d04aba11b176907a9a65d29ffd to your computer and use it in GitHub Desktop.
Save Shadows-of-Fire/312c18d04aba11b176907a9a65d29ffd to your computer and use it in GitHub Desktop.
Conversion: Infix -> Prefix
(a + b) -> + a b
((x + b) * (y - d)) -> * + x b - y d
(((a + b) / (x + y)) - r) -> - / + a b + x y r
Strategy: Parenthesis grouping, subgroup replacement.
Example (using case 3):
Split input into the following string subgroups, based on parenthesis. Parenthesis are stripped.
Input: (((a + b) / (x + y)) - r) -> ends up with 4 groups (number of open parenthesis).
This becomes parsed into the following deque:
1: ((a + b) / (x + y)) - r
2: (a + b) / (x + y)
3: a + b
4: x + y
Each group then needs to be processed to remove subgroups, which results in the following modified deque.
1: $ - r
2: $ / $
3: a + b
4: x + y
At this point, all nodes can be reprocessed to represent prefix notation, by swapping the first char with the middle char.
Note, that this step is the only step to be edited to make this output postfix notation.
1: - $ r
2: / $ $
3: + a b
4: + x y
Finally, the deque can be processed into the prefix string, by traversing the deque from the top.
To do this, pop the top group off the deque, and recursively replace any found "$"'s with the next group.
This would perform the following operations
- $ r
becomes
- / $ $ r
becomes
- / + a b $ r
becomes
- / + a b + x y r
Which is the desired output.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment