Advertisement
josiftepe

Untitled

Apr 9th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. import java.util.Stack;
  2.  
  3. public class Source {
  4. public static void main(String[] args) {
  5.  
  6. }
  7.  
  8. static String infix_to_reverse_polish(String infix) {
  9. final String ops = "=|&?<>-+/*^!~()";
  10. StringBuilder sb = new StringBuilder();
  11. Stack<Integer> s = new Stack<>();
  12. for (int i = 0; i < infix.length(); i++) {
  13. String current = new String("" + infix.charAt(i));
  14. System.out.println(current);
  15. if (current.isEmpty())
  16. continue;
  17. char c = current.charAt(0);
  18. int idx = ops.indexOf(c);
  19.  
  20. if (idx != -1) {
  21. if (s.isEmpty())
  22. s.push(idx);
  23.  
  24. else {
  25. while (!s.isEmpty()) {
  26. int prec2 = s.peek();
  27. int prec1 = idx ;
  28. if (prec2 > prec1 || (prec2 == prec1 && c != '^' && c != '!' && c != '~'))
  29. sb.append(ops.charAt(s.pop())).append(' ');
  30. else break;
  31. }
  32. s.push(idx);
  33. }
  34. }
  35. else if (c == '(') {
  36. s.push(-2);
  37. }
  38. else if (c == ')') {
  39. if(s.size() == 0) {
  40. return "e r r o r";
  41. }
  42. while (s.peek() != -2)
  43. sb.append(ops.charAt(s.pop())).append(' ');
  44. s.pop();
  45. }
  46. else {
  47. sb.append(current).append(' ');
  48. }
  49. }
  50. while (!s.isEmpty())
  51. sb.append(ops.charAt(s.pop())).append(' ');
  52. return sb.toString();
  53. }
  54.  
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement