برای درک کد: http://www.codeproject.com/Articles/405361/Converting-Postfix-Expressions-to-Infix##
//
// class used to represent intermediate expressions on the stack.
//
public class Intermediate
{
public string expr; // subexpression string
public string oper; // the operator used to create this expression
public Intermediate(string expr, string oper)
{
this.expr = expr;
this.oper = oper;
}
}
//
// PostfixToInfix
//
static string PostfixToInfix(string postfix)
{
// Assumption: the postfix expression to be processed is space-delimited.
// Split the individual tokens into an array for processing.
var postfixTokens = postfix.Split(' ');
// Create stack for holding intermediate infix expressions
var stack = new Stack<Intermediate>();
foreach(string token in postfixTokens)
{
if (token == "+" || token == "-")
{
// Get the left and right operands from the stack.
// Note that since + and - are lowest precedence operators,
// we do not have to add any parentheses to the operands.
var rightIntermediate = stack.Pop();
var leftIntermediate = stack.Pop();
// construct the new intermediate expression by combining the left and right
// expressions using the operator (token).
var newExpr = leftIntermediate.expr + token + rightIntermediate.expr;
// Push the new intermediate expression on the stack
stack.Push(new Intermediate(newExpr, token));
}
else if (token == "*" || token == "/")
{
string leftExpr, rightExpr;
// Get the intermediate expressions from the stack.
// If an intermediate expression was constructed using a lower precedent
// operator (+ or -), we must place parentheses around it to ensure
// the proper order of evaluation.
var rightIntermediate = stack.Pop();
if (rightIntermediate.oper == "+" || rightIntermediate.oper == "-")
{
rightExpr = "(" + rightIntermediate.expr + ")";
}
else
{
rightExpr = rightIntermediate.expr;
}
var leftIntermediate = stack.Pop();
if (leftIntermediate.oper == "+" || leftIntermediate.oper == "-")
{
leftExpr = "(" + leftIntermediate.expr + ")";
}
else
{
leftExpr = leftIntermediate.expr;
}
// construct the new intermediate expression by combining the left and right
// using the operator (token).
var newExpr = leftExpr + token + rightExpr;
// Push the new intermediate expression on the stack
stack.Push(new Intermediate(newExpr, token));
}
else
{
// Must be a number. Push it on the stack.
stack.Push(new Intermediate(token, ""));
}
}
// The loop above leaves the final expression on the top of the stack.
return stack.Peek().expr;
}