Interview Questions

Write a program to convert infix expression to postfix expression

Software QA/Tests Interview Questions from Microsoft


(Continued from previous question...)

Write a program to convert infix expression to postfix expression

Question:
Write a program to convert infix expression to postfix expression


maybe an answer1:


namespace InfixToPostfixString
{
class Program
{
public static Stack<char> opStack = new Stack<char>();
static void Main(string[] args)
{


Console.WriteLine(InfixToPostFix("(((A+B)+E)+(F*C))-D"));
Console.Read();
}
//little bit tricky
private static Boolean Precedence(char stackTop,char infix)
{
//here we are trying to find that if the stacktop is equal to preced[] value
char[] prec = { '(','/', '*', '+', '-',')' };
for (int i = 0; i < prec.Length; ++i)
{
if (prec[i] == stackTop)
return true;
if (prec[i] == infix)
return false;
}
return false;


}
public static StringBuilder InfixToPostFix(String infix)
{
StringBuilder postFix = new StringBuilder(); int i=0,j=0;
while (i < infix.Length)
{
if (IsThisAOperandChar(infix[i]))
{
postFix.Append(infix[i]);
}
else if(IsThisAOperatorChar(infix[i]))
{
while (opStack.Count != 0 && Precedence(opStack.Peek(), infix[i]))
{
if (opStack.Peek() == '(')
{
opStack.Pop();
break;
}
else postFix.Append(opStack.Pop());
}
if(infix[i]!=')')
opStack.Push(infix[i]);
}
else return null;
i++;
}
while (opStack.Count != 0)
{
if (opStack.Peek() == '(')
opStack.Pop();
else
postFix.Append(opStack.Pop());
}

return postFix;
}
public static bool IsThisAOperandChar(char input)
{
var asciiValue = Convert.ToInt16(input);


return ((asciiValue >= 65) && (asciiValue <= 90) || (asciiValue >= 97) && (asciiValue <= 122));
}
public static bool IsThisAOperatorChar(char input)
{
var asciiValue = Convert.ToInt16(input);


return ((asciiValue == 42) || (asciiValue == 43) || (asciiValue == 45) || (asciiValue == 47) || (asciiValue == 40) || (asciiValue == 41));

}
}
}

(Continued on next question...)

Other Interview Questions