Java examples for Data Structure:Inverse Poland Expression
convert expression To Postfix
import java.util.HashMap; import java.util.Map; import java.util.Stack; public class Main { private static String convertToPostfix(String expr) { Map<Character, Integer> opPrecedence = new HashMap<>(); opPrecedence.put('+', 0); opPrecedence.put('-', 0); opPrecedence.put('*', 1); opPrecedence.put('/', 1); Stack<Character> stack = new Stack<>(); String output = ""; int i = 0;//from w w w . j a v a2 s .c o m while (i < expr.length()) { char cur = expr.charAt(i); if (cur == ' ') { ++i; continue; } if (Character.isDigit(cur)) { String numStr = ""; while (i < expr.length() && Character.isDigit(expr.charAt(i))) { numStr += expr.charAt(i); ++i; } output += numStr; output += ' '; continue; } if (cur == '(') { stack.push(cur); ++i; continue; } if (cur == ')') { while (!stack.empty() && stack.peek() != '(') { output += stack.pop(); output += ' '; } if (stack.empty()) { throw new IllegalArgumentException("Invalid expression"); } stack.pop(); ++i; continue; } if (cur == '+' || cur == '-' || cur == '*' || cur == '/') { while (!stack.empty() && opPrecedence.containsKey(stack.peek()) && opPrecedence.get(stack.peek()) >= opPrecedence.get(cur)) { output += stack.pop(); output += ' '; } stack.push(cur); ++i; continue; } throw new IllegalArgumentException("Invalid expression"); } while (!stack.empty()) { if (stack.peek() == '(') { throw new IllegalArgumentException("Invalid expression"); } output += stack.pop(); output += ' '; } return output; } public static void main(String[] args) { String expr = "(1 - 5) * 3 + 12 * 3 / 4 * (1 - 3) / 3"; System.out.println(convertToPostfix(expr)); } }