Facebook
From Reliable Stork, 5 Years ago, written in Java.
Embed
Download Paste or View Raw
Hits: 183
  1. import java.util.*;
  2.  
  3. public class Stackp{
  4.  
  5.      static int Precedence(char ch){
  6.          
  7.         switch (ch){
  8.         case '=':
  9.             return 1;
  10.         case '+':
  11.         case '-':
  12.             return 2;
  13.  
  14.         case '*':
  15.         case '/':
  16.             return 3;
  17.  
  18.         case '^':
  19.             return 4;
  20.     }
  21.     return -1;
  22.     }
  23.      
  24.      public static String InfixToPosfix(String exp){
  25.          Stack<Character> s = new Stack<>();
  26.        
  27.          String result = "";
  28.          
  29.          for(int i = 0;i< exp.length();i++){
  30.              
  31.              char c = exp.charAt(i);
  32.              
  33.              if(Character.isLetter(c)){
  34.                  result += c;
  35.              } else if (c == '(')
  36.                 s.push(c);
  37.                   else if (c == ')')
  38.             {
  39.                 while (!s.isEmpty() && s.peek() != '(')
  40.                     result += s.pop();
  41.                  
  42.                 if (!s.isEmpty() && s.peek() != '(')
  43.                     return "Invalid Expression"; // invalid expression                
  44.                 else
  45.                     s.pop();
  46.             }
  47.              else{
  48.                  while(!s.empty() && Precedence(c) <= Precedence(s.peek()))
  49.                       result += s.pop();
  50.                  s.push(c);
  51.                  
  52.              }
  53.          }
  54.          
  55.          while(!s.empty()){
  56.              result +=s.pop();
  57.          }
  58.          
  59.          return result;
  60.      }
  61.      
  62.      
  63.      public static void main(String []args){
  64.        
  65.         String result = InfixToPosfix("S=u*c^k/D-q*g^(n-b)");
  66.         System.out.println(result);
  67.      }
  68. }