Advertisement
Guest User

Untitled

a guest
Jan 24th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. package data_structure;
  2.  
  3. import java.util.Stack;
  4.  
  5. public class infixtoposfix
  6. {
  7. static String InfixtoPostFix(char exp[])
  8. {
  9. StringBuilder builder=new StringBuilder();
  10. Stack<Character> stack=new Stack<>();
  11.  
  12. for(int i=0;i<exp.length;i++)
  13. {
  14. if(Character.isDigit(exp[i]))
  15. builder.append(exp[i]);
  16. else if(isOperator(exp[i]))
  17. {
  18. while(!stack.isEmpty()&&hasHigherPrecedence(stack.peek(),exp[i])&&!hasOpeningParenthesis(stack.peek()))
  19. {
  20. builder.append(stack.pop());
  21. }
  22.  
  23. stack.push(exp[i]);
  24. }
  25. else if(hasOpeningParenthesis(exp[i]))
  26. {
  27. stack.push(exp[i]);
  28. }
  29. else if(hasClosingParenthesis(exp[i]))
  30. {
  31. while(!stack.isEmpty()&&!hasOpeningParenthesis(stack.peek()))
  32. {
  33. builder.append(stack.pop());
  34. }
  35. stack.pop();
  36. }
  37. }
  38.  
  39. while(!stack.isEmpty())
  40. {
  41. builder.append(stack.pop());
  42. }
  43.  
  44. return builder.toString();
  45. }
  46.  
  47. private static boolean hasOpeningParenthesis(char oper)
  48. {
  49. return (oper=='('||oper=='{'||oper=='[');
  50. }
  51.  
  52. private static boolean hasClosingParenthesis(char oper)
  53. {
  54. return (oper==')'||oper=='}'||oper==']');
  55. }
  56.  
  57.  
  58.  
  59. private static boolean hasHigherPrecedence(char oper1,char oper2)
  60. {
  61. if(getPriorityIndex(oper1)>=getPriorityIndex(oper2))
  62. return true;
  63. else
  64. return false;
  65. }
  66.  
  67. private static int getPriorityIndex(char opr)
  68. {
  69. if(opr=='*'||opr=='/')
  70. return 2;
  71. else if(opr=='+'||opr=='-')
  72. return 1;
  73. else
  74. return 0;
  75. }
  76.  
  77. public static boolean isOperator(char ch)
  78. {
  79. return (ch=='+'||ch=='-'||ch=='*'||ch=='/');
  80. }
  81.  
  82. public static void main(String args[])
  83. {
  84. String expression="(3+4)*2-2";
  85. String str=InfixtoPostFix(expression.toCharArray());
  86. System.out.println("The PostFix expression conversion is "+str);
  87. }
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement