private void btnInfixToPostfix_Click(object sender, EventArgs e) { string expression = txtArray1.Text; char[] array = expression.ToCharArray(); StackList stackList = new StackList(); SNode node; char[] result = new char[array.Length]; int rIndex = 0, index = 0; while (index < array.Length) { if (array[index] >= 'a' && array[index] <= 'z') { result[rIndex] = array[index]; rIndex++; } else if (array[index] == '/' || array[index] == '*' || array[index] == '^' || array[index] == '+' || array[index] == '-') { node = new SNode(); node.Val = array[index]; if (stackList.Length == 0) { stackList.Push(node); } else { int diff = GetOperatorValue(node.Val) - GetOperatorValue(stackList.Peek().Val); if (diff > 0) { stackList.Push(node); } else { result[rIndex] = stackList.Pop().Val; rIndex++; continue; } } } index++; } while (stackList.Length != 0) { result[rIndex] = stackList.Pop().Val; rIndex++; } txtResult.Text = string.Join("", result); }
private void btnEvalPostfix_Click(object sender, EventArgs e) { char[] array = txtArray1.Text.ToCharArray(); //abc*+b- int index = 0, num, op1, op2; StackList list = new StackList(); SNode node; bool isDigit; while (index < array.Length) { isDigit = int.TryParse(array[index].ToString(), out num); if (isDigit) { node = new SNode(); node.Value = num; list.Push(node); } else { op1 = list.Pop().Value; op2 = list.Pop().Value; node = new SNode(); switch (array[index]) { case '/': node.Value = op2 / op1; break; case '*': node.Value = op2 * op1; break; case '+': node.Value = op2 + op1; break; case '-': node.Value = op2 - op1; break; case '^': node.Value = op2 ^ op1; break; } list.Push(node); } index++; } txtResult.Text = Convert.ToString(list.Peek().Value); }