【问题标题】:Convert a Postfix expression to infix and calculate the postfix and give the answer将后缀表达式转换为中缀并计算后缀并给出答案
【发布时间】:2016-03-07 23:09:39
【问题描述】:

我一直在研究这个程序,以接收一个后缀表达式,计算并打印出它的答案,并将其转换为中缀表达式。我已经得到了它的计算部分。例如,如果我输入 2 2 +(考虑到间距),它会给我 4。但是,对于它的中缀部分,它会打印出 2+。然后我尝试了它只是在没有任何间距的情况下这样做。我输入了22+。后缀不起作用,但中缀打印正确。所以我不确定如何修复这部分。这是我的代码。

 import java.util.NoSuchElementException;
 import java.util.Stack;
 public class ExpressionTree 
 {

private final String postfix;
private TreeNode root;

/**
 * Takes in a valid postfix expression and later its used to construct the expression tree.
 * The posfix expression, if invalid, leads to invalid results 
 * 
 * @param postfix   the postfix expression.
 */
public ExpressionTree(String postfix) 
{
    if (postfix == null) { throw new NullPointerException("The posfix should not be null"); }
    if (postfix.length() == 0)  { throw new IllegalArgumentException("The postfix should not be empty"); } 
    this.postfix = postfix;
}

private static class TreeNode 
{
    TreeNode left;
    char ch;
    TreeNode right;

    TreeNode(TreeNode left, char ch, TreeNode right) {
        this.left = left;
        this.ch = ch;
        this.right = right;
    }
}


private boolean isOperator(char c) {
    return c == '+' || c == '-' || c == '*' || c == '/';
}


/**
 * Constructs an expression tree, using the postfix expression
 */
public void createExpressionTree() 
{
    final Stack<TreeNode> nodes = new Stack<TreeNode>();
    for (int i = 0; i < postfix.length(); i++) 
    {
        char ch  = postfix.charAt(i);
        if (isOperator(ch)) 
        {
           TreeNode rightNode = nodes.pop();
           TreeNode leftNode = nodes.pop();
           nodes.push(new TreeNode(leftNode, ch, rightNode));
        } else 
        {
            nodes.add(new TreeNode(null, ch, null));
        }
    }
    root = nodes.pop();
}
/**
 * Returns the infix expression
 * 
 * @return  the string of infix.
 */
public String infix() 
{
    if (root == null) 
    {
        throw new NoSuchElementException("The root is empty, the tree has not yet been constructed.");
    }
    final StringBuilder infix = new StringBuilder();
    inOrder(root, infix);
    return infix.toString();
}

private void inOrder(TreeNode node, StringBuilder infix) {
    if (node != null) {
        inOrder(node.left, infix);
        infix.append(node.ch);
        inOrder(node.right, infix);
    }
}
public Double evaluate(String postfix)
{
    Stack<Double> s = new Stack<Double>();
    char[] chars = postfix.toCharArray();
    int N = chars.length;
    for(int i = 0; i < N; i++)
    {
        char ch = chars[i];
        if(isOperator(ch))
        {
            switch(ch)
            {
            case '+': s.push(s.pop() + s.pop());     break;
            case '*': s.push(s.pop() * s.pop());     break;
            case '-': s.push(-s.pop() + s.pop());    break;
            case '/': s.push(1 / s.pop() * s.pop()); break;
            }
        }
        else if(Character.isDigit(ch)) 
        {
            s.push(0.0);
            while (Character.isDigit(chars[i]))
                s.push(10.0 * s.pop() + (chars[i++] - '0'));
    }
    } 
        return s.pop();

    }
    }

这是我的测试仪:

      import java.util.Scanner;
      public class ExpressionTester

       public static void main(String[] args) 
      {
    Scanner sc = new Scanner(System.in);
    while(true)
    {
    System.out.println("");
    String pf = sc.nextLine();
    ExpressionTree eT = new ExpressionTree(pf);
    eT.createExpressionTree();
    System.out.println("The infix: " + eT.infix() );
    System.out.println(eT.evaluate(pf));
    }

    }
    }

任何帮助将不胜感激,因为我真的不知道如何解决这个问题,而且我已经接近完成它了。

【问题讨论】:

    标签: java tree postfix-notation


    【解决方案1】:
    if (isOperator(ch))
    {
        TreeNode rightNode = nodes.pop();
        TreeNode leftNode = nodes.pop();
        nodes.push(new TreeNode(leftNode, ch, rightNode));
    }
    else
    {
        nodes.add(new TreeNode(null, ch, null));
    }
    

    您将空白节点放入树中。试试这个:

    if (isOperator(ch))
    {
        TreeNode rightNode = nodes.pop();
        TreeNode leftNode = nodes.pop();
        nodes.push(new TreeNode(leftNode, ch, rightNode));
    }
    else if (!Character.isWhitespace(ch))
    {
        nodes.add(new TreeNode(null, ch, null));
    }
    

    【讨论】:

    • 谢谢!这解决了问题!
    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 2013-04-02
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 2011-05-27
    • 2013-11-12
    • 1970-01-01
    相关资源
    最近更新 更多