简体   繁体   English

带堆栈的Java Infix / Postfix转换器

[英]Java Infix / Postfix Converter with Stacks

I'm supposed to implement 3 functions in the following code. 我应该在以下代码中实现3个功能。

Functions:
    1. evaluate arithmetic expression in postfix
    2. convert arithmetic expression from infix to postfix
    3. convert arithmetic expression from postfix to infix

I don't know at all where I could start and how the functions need to look / made up at all. 我根本不知道我可以从哪里开始,以及这些函数如何看起来/组成起来。 If you could help me with just one of these 3 functions, I would probably be able to do the other 2 myself. 如果您可以仅通过这三个功能之一来帮助我,我自己就可以完成另外两个功能。

Here is the code: 这是代码:

import java.util.Stack;

public class Postfix {

    public static int evalPostfix(String postfix) {
        // TODO
    }

    public static String infixToPostfix(String infix) {
        // TODO
    }

    public static String postfixToInfix(String postfix) {
        // TODO
    }

    public static void main(String[] args) {
        String infix1 = "(3-(7*2))";
        String postfix1 = "372*-";
        int eval1 = -11;

        String infix2 = "((7+1)*((3-6)*(5-2)))";
        String postfix2 = "71+36-52-**";
        int eval2 = -72;

        System.out.println("             postfix1: " + postfix1);
        int n = evalPostfix(postfix1);
        System.out.println("evalPostfix(postfix1): " + n);
        if (n == eval1) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();

        System.out.println("                infix1: " + infix1);
        String s = infixToPostfix(infix1);
        System.out.println("infixToPostfix(infix1): " + s);
        if (s.equals(postfix1)) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();

        System.out.println("                postfix1: " + postfix1);
        s = postfixToInfix(postfix1);
        System.out.println("postfixToInfix(postfix1): " + s);
        if (s.equals(infix1)) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();

        System.out.println("             postfix2: " + postfix2);
        n = evalPostfix(postfix2);
        System.out.println("evalPostfix(postfix2): " + n);
        if (n == eval2) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();

        System.out.println("                infix2: " + infix2);
        s = infixToPostfix(infix2);
        System.out.println("infixToPostfix(infix2): " + s);
        if (s.equals(postfix2)) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();

        System.out.println("                postfix2: " + postfix2);
        s = postfixToInfix(postfix2);
        System.out.println("postfixToInfix(postfix2): " + s);
        if (s.equals(infix2)) {
            System.out.println("                       Right!");
        } else {
            System.out.println("                       Wrong!");
        }
        System.out.println();
    }
}

Here is some incomplete pseudocode to help you: 以下是一些不完整的伪代码可以帮助您:

function int evalPostfix(string postfix)

  repeat

    // Fetch the next item.
    item <- get next item from postfix

    // Process the current item.
    if (item is operand)
      push item onto stack
    else if (item is operator)
      pop required number of operands from the stack
      push operator(operands) onto stack
    else
      throw error "Unrecognised item: " + item + " found."
    end if

  until (no more items in postfix)

  return pop from stack

end function

You will need separate operator functions for each operator that your code needs to deal with. 对于代码需要处理的每个运算符,您将需要单独的运算符功能。

This is a classic 'Stack' data structure problem. 这是一个经典的“堆栈”数据结构问题。

May be you have already given it a try with Stacks (you have a stack import.), you can also solve that with regular expressions or binary trees etc, 也许您已经尝试过使用Stacks(您已经导入了堆栈),也可以使用正则表达式或二叉树等解决它,

in case you just want an idea to solve that, hope this may help: 如果您只是想一个主意来解决这个问题,希望这对您有所帮助:

infix to postfix conversion with stacks: 带栈的后缀转换的中缀:

Algorithm: 算法:

  1. Scan the input infix expression from left to right. 从左到右扫描输入的中缀表达式。
  2. If that's an operand add it to your temporary string. 如果是操作数,则将其添加到您的临时字符串中。
  3. else if the order of precedence of the operator is more than the operator in stacks or stack is empty then push it to stack. 否则,如果运算符的优先顺序大于堆栈中的运算符或堆栈为空,则将其推入堆栈。
  4. If it is '(', add that to stack. 如果为'(',则将其添加到堆栈中。
  5. else if it is ')', pop and add item to output string until an '(' comes. 否则,如果是')',则将其弹出并添加到输出字符串中,直到出现'('。
  6. keep doing 2-5 util string have more characters. 继续做2-5 util字符串有更多字符。
static Stack<String> stack;

private static String doInfixToPostfix(String exp) {
    stack = new Stack<String>();
    String output = "";
    for(int i=0;i<exp.length();i++){

        if(exp.charAt(i) == '('){
            stack.push("(");
        }
        else if(exp.charAt(i) == ')'){
            while(stack.size()>0 && stack.peek() != "("){
                output+= stack.pop();
            }
            if(stack.size()>0 && stack.peek() != "(")
                return "INVALID";
            else
                stack.pop();
        }
        else if(isOperand("" + exp.charAt(i))){
            //Its a Number
            //It could be replaced to get more than one digits.....
            output+= exp.charAt(i);;
        }
        else{
            //Its a operator
            while(stack.size()>0 && (priority("" + exp.charAt(i)) < priority(stack.peek()))){
                output += stack.pop();
            }
            stack.push("" + exp.charAt(i));
        }
    }
    while(stack.size()>0){
        output+=stack.pop();
    }
    return output;
}


private static int priority(String value) {
    if(value == "+" || value == "-") return 1;
    else if(value == "*" || value == "/") return 2;
    else if(value == "^") return 3;

    return 0;
}

//This could be modified to accept more than one digits...
private static boolean isOperand(String value) {
    try{
        Integer.parseInt(value);
    }
    catch(NumberFormatException e){return false;}
    return true;
}

and hey, instead comparing outputs by those very long code blocks, you could have simply used assertEquals() test cases. 嘿,您可以只使用assertEquals()测试用例,而不用比较那些很长的代码块比较输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM