Advertisement
Guest User

Untitled

a guest
Apr 21st, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.68 KB | None | 0 0
  1. import java.util.*;
  2. public class InfixToPostfixProgram {
  3. public static void main(String[] args) {
  4. Stack<String> stack = new Stack<String>();
  5. Scanner input = new Scanner(System.in);
  6. String exp = input.next();
  7. LinkedList <String>list= new LinkedList<String>();
  8. boolean prevPriority = false;
  9. boolean hasPriority = false;
  10. for (int i=0; i<exp.length(); i++) {
  11. String s = exp.charAt(i)+"";
  12. if(s.equals("+") || s.equals("-")) {
  13. while(!stack.isEmpty())
  14. {
  15. String tkn=stack.pop();
  16. if((tkn.equals("*") || tkn.equals("/") || tkn.equals("^")) && hasPriority == false )
  17. list.add(tkn);
  18. else if(prevPriority) {
  19. list.add(tkn);
  20. prevPriority = false;
  21. }
  22. else{
  23. stack.push(tkn);
  24. break;
  25. }
  26. }
  27. hasPriority = false;
  28. stack.push(s);
  29. }
  30. else if ((s.equals("*") || s.equals("/")))
  31. {
  32. while(!stack.isEmpty())
  33. {
  34. String tkn=stack.pop();
  35. if(tkn.equals("^") && hasPriority == false)
  36. list.add(tkn);
  37. else if(prevPriority) {
  38. list.add(tkn);
  39. prevPriority= false;
  40. }
  41. else{
  42. stack.push(tkn);
  43. break;
  44. }
  45. }
  46. hasPriority = false;
  47. stack.push(s);
  48. }
  49. else if (s.equals("^"))
  50. {
  51. while(!stack.isEmpty())
  52. {
  53. String tkn=stack.pop();
  54. if(prevPriority) {
  55. list.add(tkn);
  56. prevPriority = false;
  57. }else{
  58. stack.push(tkn);
  59. break;
  60. }
  61. }
  62. hasPriority = false;
  63. stack.push(s);
  64. }
  65.  
  66.  
  67. else if (s.equals(")"))
  68. {
  69. prevPriority = true;
  70. }
  71. else if (s.equals("(")) {
  72. hasPriority = true;
  73. }
  74. else {
  75. list.add(s);
  76. }
  77. }
  78.  
  79. while(!stack.isEmpty())
  80. {
  81. list.add(stack.pop());
  82. }
  83.  
  84. System.out.println(list);
  85.  
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement