Program hanoistack;
Uses crt;
type
TPole = (tpLeft, tpCenter, tpRight);
SLL=^data;
data=record
info:integer;
next:SLL;
end;
Node=SLL;
const
strPole:array[TPole] of string[6]=('left','center','right');
STACK_SIZE = 100;
var
L : SLL;
C : SLL;
R : SLL;
topPointerL,topPointerC,topPointerR : integer;
i, n : integer;
procedure InitStack;
begin
topPointerL := 0;
topPointerC := 0;
topPointerR := 0;
end;
function Pop(Var s :SLL):integer;
var t : SLL;
Begin
if (s<>nil) then begin
t:=s; pop:=s^.info; s:=s^.next;dispose(t);
end;
End;
Procedure Push(Var s:SLL; x:integer);
var q : SLL;
Begin
new(q);
q^.info:=x;
q^.next:=s;
s:=q;
End;
Procedure Display(s:SLL);
Begin
while s<> nil do begin
write(s^.info); s:=s^.next;
end;
writeln;
End;
procedure MoveOneDisk(const DiskNum:integer; const Origin,Destination:TPole);
begin
if strPole[Origin] = 'left' then
Pop(L)
else if strPole[Origin] = 'center' then
Pop(C)
else
Pop(R);
if strPole[Destination] = 'left' then
Push(L,DiskNum)
else if strPole[Destination] = 'center' then
Push(C,DiskNum)
else
Push(R,DiskNum);
Writeln('Move disk ',DiskNum,' from ',strPole[Origin],' to ',strPole[Destination]);
write ('L : '); display(L);
write ('C : '); display(C);
write ('R : '); display(R);
end;
procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole);
begin
if Ndisks =1 then
MoveOneDisk(1,origin,Destination)
else begin
MoveStack(Ndisks - 1, Origin,Auxiliary, Destination );
MoveOneDisk(Ndisks,origin,Destination);
MoveStack(Ndisks - 1, Auxiliary, Destination, origin);
end;
end;
procedure hanoi(var c_gerak : integer;cacah : integer; A, B, C : char);
begin
if (cacah > 0) then
begin
hanoi(c_gerak, cacah - 1, A, C, B);
c_gerak := succ(c_gerak);
write('Langkah ke ',c_gerak:3);
write(': pindah piringan nomor ',cacah:3);
write(': dari tonggak ',A);
write(': ke tonggak ',C);
writeln(' (',A,' -> ',C,')');
hanoi(c_gerak, cacah - 1, B, A, C);
end
end;
begin
Clrscr;
writeln('----------------------------------')
write('Masukan Jumlah Piringan : '); readln(n);
for i:= n downto 1 do
begin
Push(L,i);
end;
writeln('Elemen yang diinputkan ');
write ('L : '); display(L);
write ('C : '); display(C);
write ('R : '); display(R);
MoveStack(n,tpLeft,tpCenter,tpRight);
readln;
end.
Tidak ada komentar:
Posting Komentar