Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.41 KB | None | 0 0
  1. public static String infixToPostFix(String input) throws IllegalArgumentException {
  2. Stack<String> stack = new Stack<String>();
  3. String[] arr = input.split(" ");
  4. String output = "";
  5.  
  6. for (int i = 0; i < arr.length; i++) {
  7. if (!isOperator(arr[i])) {
  8. output += arr[i] + " ";
  9. continue;
  10. }
  11.  
  12. output = pushOperator(stack, arr[i], output);
  13.  
  14. }
  15. while (!stack.isEmpty()) {
  16. output += stack.pop() + " ";
  17. }
  18.  
  19. return output;
  20. }
  21.  
  22. public static String pushOperator(Stack<String> stack, String operator, String output) {
  23. String out = output;
  24.  
  25. if (stack.size() == 0) {
  26. stack.push(operator);
  27. return output;
  28. }
  29.  
  30. if (operator.equals(")")) {
  31. while (!stack.peek().equals("(")) {
  32. out += stack.pop() + " ";
  33. if (stack.isEmpty())
  34. return out;
  35. }
  36. stack.pop();
  37. return out;
  38. }
  39.  
  40. while (precedence(stack.peek()) >= precedence(operator) && !stack.peek().equals("(")) {
  41. out += stack.pop() + " ";
  42. if (stack.isEmpty()) {
  43. break;
  44. }
  45. }
  46. stack.push(operator);
  47. return out;
  48. }
  49.  
  50. public static int precedence(String operator) {
  51. switch (operator) {
  52. case ("+"):
  53. return 1;
  54. case ("-"):
  55. return 1;
  56. case ("*"):
  57. return 2;
  58. case ("/"):
  59. return 2;
  60. case ("^"):
  61. return 3;
  62. case ("("):
  63. return 4;
  64. }
  65. return -1;
  66. }
  67.  
  68. public static boolean isOperator(String input) {
  69. return input.matches("[\\+\\-\\*\\/\\(\\)]");
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement