Didart

Infix to Postfix

Dec 29th, 2022
764
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.00 KB | None | 0 0
  1. package StacksAndQueues1;
  2.  
  3. import java.util.ArrayDeque;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. import java.util.Scanner;
  7.  
  8. public class InfixToPostfix {
  9.     public static void main(String[] args) {
  10.         Scanner scanner = new Scanner(System.in);
  11.  
  12.         String[] input = scanner.nextLine().split(" ");
  13.  
  14.         ArrayDeque<String> operators = new ArrayDeque<>();
  15.         ArrayDeque<String> expression = new ArrayDeque<>();
  16.  
  17.         Map<String, Integer> priorities = new HashMap<>();
  18.         priorities.put("*", 3);
  19.         priorities.put("/", 3);
  20.         priorities.put("+", 2);
  21.         priorities.put("-", 2);
  22.         priorities.put("(", 1);
  23.  
  24.         for (String element : input) {
  25.             try {
  26.                 double num = Double.parseDouble(element);
  27.                 expression.addLast(element);
  28.             } catch (Exception e) {
  29.                 switch (element) {
  30.                     case "x":
  31.                         expression.addLast(element);
  32.                         break;
  33.                     case "(":
  34.                         operators.push(element);
  35.                         break;
  36.                     case ")":
  37.                         String symbol = operators.pop();
  38.                         while (!symbol.equals("(")) {
  39.                             expression.addLast(symbol);
  40.                             symbol = operators.pop();
  41.                         }
  42.                         break;
  43.                     default:
  44.                         while (!operators.isEmpty() && priorities.get(operators.peek()) >= priorities.get(element)) {
  45.                             expression.addLast(operators.pop());
  46.                         }
  47.                         operators.push(element);
  48.                         break;
  49.                 }
  50.             }
  51.         }
  52.         while (!operators.isEmpty()) {
  53.             expression.addLast(operators.pop());
  54.         }
  55.  
  56.         while (expression.size() > 0) {
  57.             System.out.print(expression.pop() + " ");
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment