Code kí pháp nghịch đảo Ba Lan viết bằng Pascal. học qua cấu trúc dữ liệu chắc bạn cũng biết bài này. tham khảo:
PHP Code:
program ConvertInfixToRPN;
const
Opt = ***91;'(', ')', '+', '-', '*', '/'***93;;
var
T, Infix, Stack: String;
p: Integer;
procedure StackInit;
begin
Stack := '';
end;
procedure Push(V: Char);
begin
Stack := Stack + V;
end;
function Pop: Char;
begin
Pop := Stack***91;Length(Stack)***93;;
Dec(Stack***91;0***93;);
end;
function Get: Char;
begin
Get := Stack***91;Length(Stack)***93;;
end;
procedure Refine(var S: String);
var
i: Integer;
begin
S := S + ' ';
for i := Length(S) - 1 downto 1 do
if (S***91;i***93; in Opt) or (S***91;i + 1***93; in Opt) then
Insert(' ', S, i + 1);
for i := Length(S) - 1 downto 1 do
if (S***91;i***93; = ' ') and (S***91;i + 1***93; = ' ') then Delete(S, i + 1, 1);
end;
function Priority(Ch: Char): Integer;
begin
case ch of
'*', '/': Priority := 2;
'+', '-': Priority := 1;
'(': Priority := 0;
end;
end;
procedure Process(T: String);
var
c, x: Char;
begin
c := T***91;1***93;;
if not (c in Opt) then Write(T, ' ')
else
case c of
'(': Push(c);
')': repeat
x := Pop;
if x <> '(' then Write(x, ' ');
until x = '(';
'+', '-', '*', '/':
begin
while (Stack <> '') and (Priority(c) <= Priority(Get)) do
Write(Pop, ' ');
Push(c);
end;
end;
end;
begin
Write('Infix = '); Readln(Infix);
Refine(Infix);
Writeln('Refined: ', Infix);
Write('RPN : ');
T := '';
for p := 1 to Length(Infix) do
if Infix***91;p***93; <> ' ' then T := T + Infix***91;p***93;
else
begin
Process(T);
T := '';
end;
while Stack <> '' do Write(Pop, ' ');
Writeln;
end.
--------------------------------------------------
Xem các chủ đề cùng chuyên mục: