public decimal EvaluatePostfix(string input) { LinkedListStack <decimal> stack = new LinkedListStack <decimal>(); foreach (var i in input) { if (IsOperator(i)) { decimal result; var right = decimal.Parse(stack.Pop().ToString()); var left = decimal.Parse(stack.Pop().ToString()); switch (i) { case '+': result = left + right; break; case '-': result = left - right; break; case '*': result = left * right; break; case '/': result = left / right; break; default: result = 0; break; } stack.Push(result); } else { stack.Push(decimal.Parse(i.ToString())); } } return(stack.First()); }
private string InsertParens(string input) { LinkedListStack <string> stack = new LinkedListStack <string>(); foreach (var i in input) { if (i.Equals(')')) { string expression = ")"; for (var j = 0; j < 3; j++) { expression = stack.Pop() + expression; } expression = "(" + expression; stack.Push(expression); } else { stack.Push(i.ToString()); } } return(stack.First()); }