Advertisement
John_IV

Untitled

Jan 18th, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. package M03Java_Advanced.C01Java_Advanced.L01Stacks_and_Queues.Stacks_and_Queues_Exercises;
  2.  
  3. import java.util.LinkedList;
  4. import java.util.List;
  5. import java.util.Scanner;
  6. import java.util.Stack;
  7.  
  8. public class E09InfixToPostfix {
  9.     public static void main(String[] args) {
  10.         Scanner sc = new Scanner(System.in);
  11.  
  12.         List<Character> result = new LinkedList<>();
  13.         Stack<Character> stack = new Stack<>();
  14.         String[] input = sc.nextLine().split(" ");
  15.  
  16.         for (String s : input) {
  17.             char ch = s.charAt(0);
  18.  
  19.             if (Character.isLetterOrDigit(ch)) {
  20.                 result.add(ch);
  21.  
  22.             } else if (ch == '(') {
  23.                 stack.push(ch);
  24.  
  25.             } else if (ch == ')') {
  26.  
  27.                 while (!stack.isEmpty() && stack.peek() != '(') {
  28.                     result.add(stack.pop());
  29.                 }
  30.  
  31.                 stack.pop();
  32.  
  33.             } else {
  34.  
  35.                 while (!stack.isEmpty() && precedence(ch) <= precedence(stack.peek())) {
  36.                     result.add(stack.pop());
  37.                 }
  38.  
  39.                 stack.push(ch);
  40.             }
  41.         }
  42.  
  43.         while (!stack.isEmpty()){
  44.             result.add(stack.pop());
  45.         }
  46.  
  47.         System.out.println(result.toString().replaceAll("[\\[\\],]", ""));
  48.     }
  49.  
  50.     private static int precedence(char ch)
  51.     {
  52.         switch (ch)
  53.         {
  54.             case '+':
  55.             case '-':
  56.                 return 1;
  57.  
  58.             case '*':
  59.             case '/':
  60.                 return 2;
  61.  
  62.             case '^':
  63.                 return 3;
  64.         }
  65.         return -1;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement