Skip to content

Instantly share code, notes, and snippets.

@sudipto80
Created January 7, 2016 10:53
Show Gist options
  • Save sudipto80/623c9b399bed7bb03936 to your computer and use it in GitHub Desktop.
Save sudipto80/623c9b399bed7bb03936 to your computer and use it in GitHub Desktop.
Infix Evaluation using Stack
string ops = "+-*/";
string vals = "1234567890";
Stack<char> opStack = new Stack<char>();
Stack<int> valStack = new Stack<int>();
void Main()
{
string expr = "(1 + ((2+3)*(4*5)))";
foreach (char c in expr)
{
if(vals.Contains(c.ToString()))
valStack.Push(Convert.ToInt32(c.ToString()));
if(ops.Contains(c.ToString()))
opStack.Push(c);
if(c == '(')
//ignore
continue;
if(c ==')')
{
int x = valStack.Pop();
int y = valStack.Pop();
char op = opStack.Pop();
if(op == '+')
valStack.Push(x + y);
if(op == '-')
valStack.Push(x - y);
if(op == '*')
valStack.Push(x * y);
if(op == '/')
valStack.Push(x / y);
}
//valStack.Dump("Value Stack");
//opStack.Dump("Op stack");
}
valStack.Dump("Result is");
}
// Define other methods and classes here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment