예제 #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;
  }
예제 #2
0
 public static LinkedList<MyNode> convert(LinkedList<MyNode> inFixExp) {
   LinkedList<MyNode> toReturn = new LinkedList<MyNode>();
   MyNode thisNode;
   MyNode topOperator;
   Stack theStack = new Stack();
   for (MyNode t : inFixExp) {
     thisNode = t;
     if (thisNode.getOp() == '0') // Node is a double
     toReturn.add(thisNode);
     else { // Node is an operator
       if (thisNode.getOp() == '(') theStack.push(thisNode);
       else if (thisNode.getOp() == ')') { // Node is right parens
         while (((MyNode) theStack.peek()).getOp() != '(') {
           toReturn.add((MyNode) theStack.pop());
         }
         theStack.pop();
       } else if (theStack.empty()) theStack.push(thisNode);
       else {
         topOperator = (MyNode) theStack.peek();
         if (hasPrecedence(
             thisNode.getOp(),
             topOperator.getOp())) { // operator has precedence over top operator of stack
           theStack.push(thisNode);
         } else { // operator does not have precedence over top operator of stack
           toReturn.add((MyNode) theStack.pop());
           theStack.push(thisNode);
         }
       }
     }
   }
   // all items have been seen
   while (!theStack.empty()) {
     toReturn.add((MyNode) theStack.pop());
   }
   return toReturn;
 }