Skip to content

Instantly share code, notes, and snippets.

@robsonalves
Last active May 1, 2020 06:12
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 robsonalves/aa5b1978762eb19d5101352da8919ecb to your computer and use it in GitHub Desktop.
Save robsonalves/aa5b1978762eb19d5101352da8919ecb to your computer and use it in GitHub Desktop.
Infix to Postfix
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
//Console.Write("Infix Formule: ");
//string infix = Console.ReadLine();
string infix = "4.5+a5+.1215 + 1";
String postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
infix = "(5.0 / .9)*(fahrenheit - 32)";
postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
infix = "3.1123123 * diameter";
postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
infix = "pi*r^2";
postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
infix = "a + b * c ^ d - e";
postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
infix = "a ^ b + c * d";
postfix = InfixToPostfix(infix);
Console.WriteLine("InFix :\t" + infix);
Console.WriteLine("PostFix :\t" + postfix);
}
public static string InfixToPostfix(string exp)
{
String result = String.Empty;
Stack<char> stack = new Stack<char>();
for (int i = 0; i<exp.Length; ++i)
{
char c = exp[i];
if (Char.IsLetterOrDigit(c) || Char.IsWhiteSpace(c) || c == '.')
result += c;
else if (c == '(')
stack.Push(c);
else if (c == ')')
{
while (stack.Count!=0 && stack.Peek() != '(')
result += " " + stack.Pop();
//Close () and clean from stack
if (stack.Count!=0 && stack.Peek() != '(')
return "Invalid Expression"; // invalid expression
else
stack.Pop();
}
else // an operator is encountered
{
while (stack.Count!=0 && precedence(c) <= precedence(stack.Peek()))
{
result += " " + stack.Pop();
}
result += " ";
stack.Push(c);
}
}
while (stack.Count!=0 )
result += " " + stack.Pop();
//return result.Trim();
return System.Text.RegularExpressions.Regex.Replace(result,@"\s+"," ");
}
public static int precedence(char operand)
{
switch (operand)
{
case '+':
case '-':
return 1;
case '*':
case '/':
return 2;
case '^':
return 3;
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment