package java_programs;
import java.util.*;

/**
 * 
 * @author derricklin
 */
public class SHUNTING_YARD {
    public static List<Object> shunting_yard(ArrayList<Object> tokens) {
        Map<String, Integer> precedence = new HashMap<>();
        precedence.put("+", 1);
        precedence.put("-", 1);
        precedence.put("*", 2);
        precedence.put("/", 2);

        List<Object> rpntokens = new ArrayList<>(tokens.size());
        Deque<String> opstack = new ArrayDeque<>();

        for (Object token : tokens) {
            if (token instanceof Integer || token instanceof Double) {
                rpntokens.add(token);
            } else if (token instanceof String) {
                String operator = (String) token;
                while (!opstack.isEmpty() &&
                        precedence.get(opstack.peek()) >= precedence.get(operator)) {
                    rpntokens.add(opstack.pop());
                }
                opstack.push(operator);
            }
        }

        while (!opstack.isEmpty()) {
            rpntokens.add(opstack.pop());
        }

        return rpntokens;
    }
}