Guest User

toPostfix

a guest
Apr 27th, 2021
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. class ToPostfix{
  2.  
  3.  
  4. private Stack theStack;
  5. private String input;
  6. private Queue queue;
  7.  
  8.  
  9. public ToPostfix(String in){
  10. input = in;
  11. int stackSize = input.length();
  12. int queueSize = input.length();
  13. queue = new Queue(queueSize);
  14. theStack = new Stack(stackSize);
  15. }
  16.  
  17.  
  18. public String trabslation(){
  19. for(int j=0; j<input.length(); j++)
  20. {
  21. char ch = input.charAt(j);
  22. switch(ch)
  23. {
  24. case '+':
  25. case '-':
  26. operand(ch, 1);
  27. break;
  28.  
  29. case '*':
  30. case '/':
  31. operand(ch, 2);
  32. break;
  33.  
  34. case '(':
  35. theStack.push(ch);
  36. break;
  37.  
  38. case ')':
  39. parent(ch);
  40. break;
  41.  
  42. default:
  43. queue.enqueue(ch);
  44. break;
  45. }
  46. }
  47.  
  48. while( !theStack.isEmpty()){
  49. queue.enqueue(theStack.pop());
  50. }
  51. return queue.getString();
  52. }
  53.  
  54.  
  55. public void operand(char opThis, int prec1){
  56. while( !theStack.isEmpty()){
  57.  
  58. char opTop = theStack.pop();
  59.  
  60. if( opTop == '(' ){
  61. theStack.push(opTop);
  62. break;
  63. }else{
  64. int prec2;
  65. if(opTop=='+' || opTop=='-')
  66. prec2 = 1;
  67. else
  68. prec2 = 2;
  69. if(prec2 < prec1){
  70. theStack.push(opTop);
  71. break;
  72. }
  73. else
  74. queue.enqueue(opTop);
  75. }
  76. }
  77. theStack.push(opThis);
  78. }
  79.  
  80.  
  81. public void parent(char ch){
  82. while( !theStack.isEmpty()){
  83. char chx = theStack.pop();
  84. if( chx == '(' )
  85. break;
  86. else
  87. queue.enqueue(chx);
  88. }
  89. }
  90.  
  91. }
Advertisement
Add Comment
Please, Sign In to add comment