Plange


shuntingYard.pge

<String> ops = "-+/*^";
<Stack<Int>> s;
String result = "";

for (token ∈ input("Enter expression").split(" ")) {
    c := token[0];
    idx := ops.indexOf(c);
    
    //check for operator
    if (idx ≠ -1) {
        if (s.empty) {
            s.push(idx);
        } else {
            while (¬s.empty) {
                prec2 := s.peek() / 2;
                prec1 := idx / 2;
                if (prec2 > prec1 ∨ (prec2 = prec1 ∧ c ≠ '^')) {
                    result = result + ops[s.pop()] + ' ';
                } else {
                    break;
                }
                s.push(idx);
            }
        }
    } elif (c = '(') {
        s.push(-2);
    } elif (c == ')') {
        while (s.peek() ≠ -2) {
            result = result + ops[s.pop()] + ' ';
        }
        s.pop();
    } else {
        result = result + token + ' ';
    }
}
while (¬s.empty) {
    result = result + ops[s.pop()] + ' ';
}

print(result);

copyright © Brent Lewis 2017