Advertisement
vaakata

Ex12_InfixToPostfixV20_25Jan2017

Jan 26th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.20 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class Ex12_InfixToPostfixV20_25Jan2017 {
  4.     public static void main(String[] args) {
  5.         Locale.setDefault(Locale.ROOT);
  6.  
  7.         Scanner sc = new Scanner(System.in);
  8.  
  9.         String[] input = sc.nextLine().split("\\s+");
  10.         Deque<String> numbersQueue = new ArrayDeque<>();
  11.         Deque<String> operatorStack = new ArrayDeque<>();
  12.  
  13.  
  14.         for (String s : input) {
  15.             if(Character.isDigit(s.charAt(0)) || Character.isLetter(s.charAt(0))) {
  16.                 numbersQueue.offer(s);
  17.             } else {
  18.                 if (operatorStack.isEmpty()){
  19.                     operatorStack.push(s);
  20.                 } else {
  21.                     String lastOperator = operatorStack.peek();
  22.                     if (s.equals("+") || s.equals("-")) {
  23.                         if (lastOperator.equals("(")) {
  24.                             operatorStack.push(s);
  25.                         } else {
  26.                             numbersQueue.offer(operatorStack.pop());
  27.                             operatorStack.push(s);
  28.                         }
  29.                     } else if (s.equals("*") || s.equals("/")) {
  30.                         if (lastOperator.equals("*") || lastOperator.equals("/")) {
  31.                             numbersQueue.offer(operatorStack.pop());
  32.                             operatorStack.push(s);
  33.                         } else {
  34.                             operatorStack.push(s);
  35.                         }
  36.                     } else if (s.equals("(")) {
  37.                         operatorStack.push(s);
  38.                     } else if (s.equals(")")) {
  39.                         while (!operatorStack.peek().equals("(")) {
  40.                             numbersQueue.offer(operatorStack.pop());
  41.                         }
  42.                         //Removing the non-necessary open parenthesis '('
  43.                         operatorStack.pop();
  44.                     }
  45.                 }
  46.             }
  47.         }
  48.  
  49.         while (!numbersQueue.isEmpty()){
  50.             System.out.print(numbersQueue.poll() + " ");
  51.         }
  52.  
  53.         while (!operatorStack.isEmpty()){
  54.             System.out.print(operatorStack.pop() + " ");
  55.         }
  56.         System.out.println();
  57.     }
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement