Advertisement
Guest User

Untitled

a guest
Oct 15th, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.00 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class infix_to_postfix {
  4.  
  5. public infix_to_postfix(){}
  6.  
  7. static int prioridade(char token){
  8. switch(token){
  9. case '+':
  10. case '-':
  11. return 1;
  12.  
  13. case '*':
  14. case '/':
  15. return 2;
  16. }
  17. return 0;
  18. }
  19.  
  20. public String infix_to_postfix(String[] infix){
  21.  
  22. Stack <Character> stack = new Stack();
  23. String postfix = "";
  24. char c;
  25. String current = "";
  26.  
  27. for (int i = 0; i < infix.length; i++){
  28. current = infix[i];
  29. c = current.charAt(0);
  30.  
  31. //is number
  32. if (c >= '0' && c <= '9'){
  33. postfix += current;
  34. postfix += " ";
  35. }
  36.  
  37.  
  38. else if (stack.isEmpty() || (stack.top() == '(')){
  39. stack.push(c);
  40. }
  41.  
  42. else if (c == '('){
  43. stack.push(c);
  44. }
  45.  
  46. else if (c == ')'){
  47. while (c !='('){
  48. postfix += stack.pop();
  49. i++;
  50. current = infix[i];
  51. }
  52. stack.pop();
  53. }
  54. else if ((c == '*' || c == '/') && (!stack.isEmpty() || stack.top() == '+' || stack.top() == '-')){
  55. stack.push(c);
  56. }
  57.  
  58. else if (c == stack.top()){
  59. postfix += stack.pop() + " ";
  60. stack.push(c);
  61. }
  62.  
  63. else if ((c == '+' || c == '-') && (!stack.isEmpty() || stack.top() == '*' || stack.top() == '/')){
  64. while (!stack.isEmpty() && (stack.top() != '+' || stack.top() != '-')){
  65. postfix += stack.pop() + " ";
  66. }
  67. //postfix += stack.pop() + " ";
  68. stack.push(c);
  69. }
  70. }
  71.  
  72. while (!stack.isEmpty()){
  73. postfix += stack.pop() + " ";
  74. }
  75.  
  76. return postfix;
  77. }
  78.  
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement