How to convert a prefix notation (Polish notation) to infix notation. The record may contain: '(', ')', '+', '-', '*', '/', '0..9', 'a..z'. Tell me the algorithm for solving this problem (description, Pascal, C #), what data structures should I use?
2 answers
The obvious honest algorithm is to parse the Polish entry into the tree. Having a tree, you can recursively build any form of record (as well as optimize, compile and execute, whatever).
To record
− 5 * 6 7
you take the following steps:
- You see a minus, allocate the node of a binary operation with two operands.
- Read the first operand.
- see
5
, this is the first operand, allocating for it a leaf node with a constant
- see
- Read the second operand.
- see
*
, allocate for it a binary operation node with two operands - read the first operand
- see
6
, blocking for him a leaf node with a constant - see
7
, allocate for it a leaf node with a constant
- see
- see
For a specific task, you can simplify the result, and not build a tree, but immediately output the data. The algorithm will be as follows:
- Read one token
- If it is a constant, it is the result.
- If this is a binary operation, remember its type, recursively obtain the value of the operands, output the expression, enclose it in brackets, so as not to think about the priority of operators.
- add rules for other types of knots to taste
|
If the extra parentheses as a result is not a problem, then you can convert it with ordinary recursion:
class Program { static void Main(string[] args) { string source = "- * / 15 - 7 + 1 1 3 + 2 + 1 1"; var tokens = new Queue<string>(source.Split()); Console.WriteLine(DoConvert(tokens)); } private static string[] operators = new string[] { "+", "-", "*", "/" }; private static string DoConvert(Queue<string> tokens) { var token = tokens.Dequeue(); if (operators.Contains(token)) { return String.Format("({0} {1} {2})", DoConvert(tokens), token, DoConvert(tokens)); } else { return token; } } }
|
-a
and- ab
- PashaPash ♦5 7 -
? Is it unary minus or binary? And if so:5 7 - *
? - VladD