function IsOperator(const ch: Char): Boolean; begin Result := (ch = '+') or (ch = '-') or (ch = '*') or (ch = '/') or (ch = '^'); end; function GetPrecedence(const op: Char): Integer; begin case op of '+', '-': Result := 1; '*', '/': Result := 2; '^': Result := 3; else Result := 0; end; end; function ConvertToRPN(const expression: string): string; var stack: string; output: string; i: Integer; ch: Char; begin stack := ''; output := ''; for i := 1 to Length(expression) do begin ch := expression[i]; if ch in ['A'..'Z', 'a'..'z'] then begin output := output + ch; end else if ch in ['0'..'9'] then begin output := output + ch; end else if IsOperator(ch) then begin while (Length(stack) > 0) and IsOperator(stack[Length(stack)]) and (GetPrecedence(stack[Length(stack)]) >= GetPrecedence(ch)) do begin output := output + ' ' + stack[Length(stack)]; Delete(stack, Length(stack), 1); end; stack := stack + ch; end else if ch = '(' then begin stack := stack + ch; end else if ch = ')' then begin while (Length(stack) > 0) and (stack[Length(stack)] <> '(') do begin output := output + ' ' + stack[Length(stack)]; Delete(stack, Length(stack), 1); end; // Remove the '(' from the stack Delete(stack, Length(stack), 1); end; end; // Pop any remaining operators from the stack to the output while Length(stack) > 0 do begin output := output + ' ' + stack[Length(stack)]; Delete(stack, Length(stack), 1); end; Result := output; end;