Re: ПАСКАЛЬ - СПИСКИ
Добавлено: 09 май 2007, 04:22
А вот и решение. Процедура add2tail не пригодилась (тут ее можно выкинуть), но не стал ее удалять, вдруг кому понадобится.
Код: Выделить всё
type
TValue = integer;
PItem = ^TItem;
TItem = record
inf: TValue;
next: PItem;
end;
var
p1,p2,p3:PItem;
function endof(list:PItem):PItem;
{Finds the last item of the list}
begin
if list<>nil then while list^.next<>nil do list:=list^.next;
endof:=list;
end;
procedure add2head(val:TValue; var list:PItem);
{Adds new first item to the list}
var
p:PItem;
begin
new(p);
p^.inf:=val;
p^.next:=list;
list:=p;
end;
procedure add2tail(val:integer; var list:PItem);
{Adds new last item to the list}
var
p,t:PItem;
begin
new(p);
p^.inf:=val;
p^.next:=nil;
t:=endof(list);
if t=nil then list:=p else t^.next:=p;
end;
procedure print(list:PItem);
{Prints comma separated list to the screen}
var
r:integer;
begin
r:=0;
write('Содержание списка: ');
while list<>nil do begin
write(list^.inf);
if list^.next<>nil then write(', ') else writeln('.');
list:=list^.next;
inc(r);
end;
writeln('Всего ',r,' элементов');
end;
procedure JoinOrderedABtoC(var a,b,c:PItem);
var
l1,l2,t:PItem;
begin
if a=nil then c:=b else if b=nil then c:=a else begin
if a^.inf<=b^.inf then begin
l1:=a; l2:=b;
end else begin
l1:=b; l2:=a;
end;
c:=l1;
while (l1^.next<>nil) and (l2<>nil) do begin
if l1^.next^.inf>l2^.inf then begin
t:=l2;
l2:=l1^.next;
l1^.next:=t;
end;
l1:=l1^.next;
end;
if l1^.next=nil then l1^.next:=l2;
end;
end;
begin
p1:=nil; p2:=nil;
add2head(9,p1);
add2head(5,p1);
add2head(2,p1);
add2head(1,p1);
add2head(1,p1);
print(p1);
add2head(8,p2);
add2head(4,p2);
add2head(3,p2);
add2head(0,p2);
print(p2);
JoinOrderedABtoC(p1, p2, p3);
print(p3);
readln;
end.