Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static String infixToPostFix(String input) throws IllegalArgumentException {
- Stack<String> stack = new Stack<String>();
- String[] arr = input.split(" ");
- String output = "";
- for (int i = 0; i < arr.length; i++) {
- if (!isOperator(arr[i])) {
- output += arr[i] + " ";
- continue;
- }
- output = pushOperator(stack, arr[i], output);
- }
- while (!stack.isEmpty()) {
- output += stack.pop() + " ";
- }
- return output;
- }
- public static String pushOperator(Stack<String> stack, String operator, String output) {
- String out = output;
- if (stack.size() == 0) {
- stack.push(operator);
- return output;
- }
- if (operator.equals(")")) {
- while (!stack.peek().equals("(")) {
- out += stack.pop() + " ";
- if (stack.isEmpty())
- return out;
- }
- stack.pop();
- return out;
- }
- while (precedence(stack.peek()) >= precedence(operator) && !stack.peek().equals("(")) {
- out += stack.pop() + " ";
- if (stack.isEmpty()) {
- break;
- }
- }
- stack.push(operator);
- return out;
- }
- public static int precedence(String operator) {
- switch (operator) {
- case ("+"):
- return 1;
- case ("-"):
- return 1;
- case ("*"):
- return 2;
- case ("/"):
- return 2;
- case ("^"):
- return 3;
- case ("("):
- return 4;
- }
- return -1;
- }
- public static boolean isOperator(String input) {
- return input.matches("[\\+\\-\\*\\/\\(\\)]");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement