Advertisement
dxvmxnd

Untitled

Apr 17th, 2024 (edited)
27
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. function IsOperator(const ch: Char): Boolean;
  2. begin
  3. Result := (ch = '+') or (ch = '-') or (ch = '*') or (ch = '/') or (ch = '^');
  4. end;
  5.  
  6. function GetPrecedence(const op: Char): Integer;
  7. begin
  8. case op of
  9. '+', '-': Result := 1;
  10. '*', '/': Result := 2;
  11. '^': Result := 3;
  12. else
  13. Result := 0;
  14. end;
  15. end;
  16.  
  17. function ConvertToRPN(const expression: string): string;
  18. var
  19. stack: string;
  20. output: string;
  21. i: Integer;
  22. ch: Char;
  23. begin
  24. stack := '';
  25. output := '';
  26.  
  27. for i := 1 to Length(expression) do
  28. begin
  29. ch := expression[i];
  30. if ch in ['A'..'Z', 'a'..'z'] then
  31. begin
  32. output := output + ch;
  33. end
  34. else if ch in ['0'..'9'] then
  35. begin
  36. output := output + ch;
  37. end
  38. else if IsOperator(ch) then
  39. begin
  40. while (Length(stack) > 0) and IsOperator(stack[Length(stack)]) and (GetPrecedence(stack[Length(stack)]) >= GetPrecedence(ch)) do
  41. begin
  42. output := output + ' ' + stack[Length(stack)];
  43. Delete(stack, Length(stack), 1);
  44. end;
  45. stack := stack + ch;
  46. end
  47. else if ch = '(' then
  48. begin
  49. stack := stack + ch;
  50. end
  51. else if ch = ')' then
  52. begin
  53. while (Length(stack) > 0) and (stack[Length(stack)] <> '(') do
  54. begin
  55. output := output + ' ' + stack[Length(stack)];
  56. Delete(stack, Length(stack), 1);
  57. end;
  58. // Remove the '(' from the stack
  59. Delete(stack, Length(stack), 1);
  60. end;
  61. end;
  62.  
  63. // Pop any remaining operators from the stack to the output
  64. while Length(stack) > 0 do
  65. begin
  66. output := output + ' ' + stack[Length(stack)];
  67. Delete(stack, Length(stack), 1);
  68. end;
  69.  
  70. Result := output;
  71. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement