Advertisement
Guest User

Untitled

a guest
Feb 26th, 2017
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.43 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class Demo{
  4.  
  5. public static void main(String[] args){
  6.  
  7. String infixExp = "a + b * c + ( d * e + f ) * g";
  8.  
  9. System.out.println(infixToPostFix(infixExp));
  10.  
  11. }
  12.  
  13. public static String infixToPostFix(String infixExp) {
  14. // provide implementation here
  15. Stack<String> operators = new Stack<String>();
  16. String s1 = "";
  17.  
  18. String[] split = infixExp.trim().split("\s+");
  19.  
  20. for(int i = 0; i < split.length; i++){
  21. if(split[i].matches("[^()*/%+-]")){
  22. s1 = s1 + split[i] + " ";
  23. }else{
  24. switch(split[i]){
  25. case "(":
  26. operators.push(split[i]);
  27. break;
  28. case ")":
  29. while(operators.peek() != "("){ s1 = s1 + operators.pop() + " "; }
  30. operators.pop();
  31. break;
  32. case "*":
  33. case "/":
  34. case "%":
  35. operators.push(split[i]);
  36. break;
  37. case "+":
  38. case "-":
  39. if(!operators.isEmpty()){
  40. while(operators.peek() == "*" || operators.peek() == "/" || operators.peek() == "%" ){
  41. s1 = s1 + operators.pop() + " ";
  42. }
  43. }
  44.  
  45. operators.push(split[i]);
  46. break;
  47. }
  48. }
  49. }
  50.  
  51. return s1;
  52.  
  53. }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement