Advertisement
goodvibes2298

Splitter01

Jan 27th, 2023
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. public static Stack<String> splitter(String exp) {
  2.  
  3. String str = exp.replaceAll("\\s", "");
  4.  
  5. Stack<String> stack = new Stack<String>();
  6. Stack<String> ReverseStack = new Stack<String>();
  7. char[] cArr = str.toCharArray();
  8.  
  9. Stack<String> stackOutput = new Stack<String>();
  10. String helper = "";
  11. char lastChar = ' ';
  12.  
  13.  
  14. for(int i = 0; i<str.length(); i++) {
  15.  
  16. if (str.charAt(i) == ('-') && lastChar == '(') {
  17. if(!stack.empty()) {
  18. while(!stack.empty())
  19. ReverseStack.push(stack.pop());
  20.  
  21. while(!ReverseStack.empty())
  22. helper += ReverseStack.pop();
  23.  
  24. stackOutput.push(helper);
  25. helper = "";
  26. }
  27. stack.push(String.valueOf(str.charAt(i)));
  28.  
  29.  
  30. }
  31. else if(str.charAt(i) == ('(') || str.charAt(i) == ('+') || str.charAt(i) == (')')
  32. ||str.charAt(i) == ('*') ||str.charAt(i) == ('/') ||str.charAt(i) == ('^') || str.charAt(i) == ('-') && i != 0 ){
  33.  
  34. if(!stack.empty()) {
  35. while(!stack.empty())
  36. ReverseStack.push(stack.pop());
  37.  
  38. while(!ReverseStack.empty())
  39. helper += ReverseStack.pop();
  40.  
  41. stackOutput.push(helper);
  42. helper = "";
  43. }
  44. stack.push(String.valueOf(str.charAt(i)));
  45.  
  46. if(!stack.empty()) {
  47. while(!stack.empty())
  48. ReverseStack.push(stack.pop());
  49.  
  50. while(!ReverseStack.empty())
  51. helper += ReverseStack.pop();
  52.  
  53. stackOutput.push(helper);
  54. helper = "";
  55. }
  56. }
  57.  
  58. else
  59. stack.push(String.valueOf(str.charAt(i)));
  60.  
  61. lastChar = str.charAt(i);
  62.  
  63. }
  64.  
  65. if(!stack.empty()) {
  66. while(!stack.empty())
  67. ReverseStack.push(stack.pop());
  68.  
  69.  
  70. while(!ReverseStack.empty())
  71. helper += ReverseStack.pop();
  72.  
  73. stackOutput.push(helper);
  74. helper = "";
  75. }
  76.  
  77. return stackOutput;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement