Exemplo n.º 1
0
  public static Double eval(LinkedList<MyNode> postfixExp) {
    Stack theStack = new Stack();
    Double temp;
    Double newVal = 0.0;
    Double under;
    char op;
    String evaluate;
    MyNode thisNode;

    for (MyNode t : postfixExp) {
      thisNode = t;
      if (thisNode.getOp() == '0') theStack.push(thisNode.getValue());
      else {
        // want to check if r/l/s, if thats the case, just pull top, apply operator, push
        if (thisNode.getOp() == 'r' || thisNode.getOp() == 'l' || thisNode.getOp() == 's') {
          op = thisNode.getOp();
          temp = (Double) theStack.pop();
          switch (op) {
            case 'l':
              newVal = Math.log(temp);
              break;
            case 'r':
              newVal = (Double) (1 / temp);
              break;
            case 's':
              newVal = Math.sqrt(temp);
              break;
          }
          theStack.push(newVal);

        } else {
          temp = (Double) theStack.pop();
          under = (Double) theStack.pop();
          op = thisNode.getOp();
          switch (op) {
            case '+':
              newVal = under + temp;
              break;
            case '-':
              newVal = under - temp;
              break;
            case '/':
              newVal = under / temp;
              break;
            case '*':
              newVal = under * temp;
              break;
            case '^':
              newVal = Math.pow(under, temp);
              break;
            default:
              break;
          }
          theStack.push(newVal);
        }
      }
    }
    Double toReturn = (Double) theStack.pop();
    return toReturn;
  }