How to calculate output of Infix-Expression by using stacks in C#

白昼怎懂夜的黑 提交于 2019-12-31 05:29:12

问题


I already found different solutions on Stackoverflow, but there were some things I didn´t understand.

Whats the best method to calculate the Output of e.g.: ((1+(4*(2+3)))+((2+3)*(4*5))) ?

My method looks as following, but I know there are lots of mistakes in it:

public static int ComputeInfix(string infix) {
        Stack<char> operatorstack = new Stack<char>();
        Stack<int> operandstack = new Stack<int>();
        for(int j = 0; j < infix.Length; j++) {
            char c = infix[j];
            if (c => 0 && c <= 9) {
                operandstack.Push(c);
            }
            else if ((c == '+' || c == '*' ||  c == '/' || c == '-')) {
                if (operatorstack.IsEmpty()) {
                    operatorstack.Push(c);
                }
                else {
                    if (operatorstack.Peek() != '*' || operatorstack.Peek() != '/') {
                        operatorstack.Push(c);
                    }
                }
            } 
            else if (c == '(') {
                operatorstack.Push(c);
            }
            else if (c == ')') {
                operatorstack.Pop();
            }
        }
        return infix;
    }

Now changed it to:

Stack<char> operatorstack = new Stack<char>();
        Stack<char> operandstack = new Stack<char>();
        for(int j = 0; j < infix.Length; j++) {
            char c = infix[j];
            if (c => '0' && c <= '9') {
                operandstack.Push(c);
            }

But get error:

Infix.cs(16,8): error CS0136: A local variable named c' cannot be declared in this scope because it would give a different meaning to c', which is already used in a `parent or current' scope to denote something else


回答1:


Since I spent the time to write it, here is my solution:

public static int ComputeInfix(string infix) {
    var operatorstack = new Stack<char>();
    var operandstack = new Stack<int>();

    var precedence = new Dictionary<char, int> { { '(', 0 }, { '*', 1 }, { '/', 1 }, { '+', 2 }, { '-', 2 }, { ')', 3 } };

    foreach (var ch in $"({infix})") {
        switch (ch) {
            case var digit when Char.IsDigit(digit):
                operandstack.Push(Convert.ToInt32(digit.ToString()));
                break;
            case var op when precedence.ContainsKey(op):
                var keepLooping = true;
                while (keepLooping && operatorstack.Count > 0 && precedence[ch] > precedence[operatorstack.Peek()]) {
                    switch (operatorstack.Peek()) {
                        case '+':
                            operandstack.Push(operandstack.Pop() + operandstack.Pop());
                            break;
                        case '-':
                            operandstack.Push(-operandstack.Pop() + operandstack.Pop());
                            break;
                        case '*':
                            operandstack.Push(operandstack.Pop() * operandstack.Pop());
                            break;
                        case '/':
                            var divisor = operandstack.Pop();
                            operandstack.Push(operandstack.Pop() / divisor);
                            break;
                        case '(':
                            keepLooping = false;
                            break;
                    }
                    if (keepLooping)
                        operatorstack.Pop();
                }
                if (ch == ')')
                    operatorstack.Pop();
                else
                    operatorstack.Push(ch);
                break;
            default:
                throw new ArgumentException();
        }
    }

    if (operatorstack.Count > 0 || operandstack.Count > 1)
        throw new ArgumentException();

    return operandstack.Pop();
}


来源:https://stackoverflow.com/questions/44188609/how-to-calculate-output-of-infix-expression-by-using-stacks-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!