Created
January 7, 2016 10:53
-
-
Save sudipto80/623c9b399bed7bb03936 to your computer and use it in GitHub Desktop.
Infix Evaluation using Stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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