用类Pascal语言写一个归并两升序循环链表的算法
时间: 2023-05-20 16:04:07 浏览: 67
以下是一个用类Pascal语言写的归并两升序循环链表的算法:
type
NodePtr = ^Node;
Node = record
data: Integer;
next: NodePtr;
end;
function MergeSortedCircularLists(list1, list2: NodePtr): NodePtr;
var
head, tail: NodePtr;
begin
if (list1 = nil) then
begin
MergeSortedCircularLists := list2;
Exit;
end
else if (list2 = nil) then
begin
MergeSortedCircularLists := list1;
Exit;
end;
if (list1^.data < list2^.data) then
begin
head := list1;
list1 := list1^.next;
end
else
begin
head := list2;
list2 := list2^.next;
end;
tail := head;
while (list1 <> nil) and (list2 <> nil) do
begin
if (list1^.data < list2^.data) then
begin
tail^.next := list1;
list1 := list1^.next;
end
else
begin
tail^.next := list2;
list2 := list2^.next;
end;
tail := tail^.next;
end;
if (list1 <> nil) then
tail^.next := list1
else
tail^.next := list2;
MergeSortedCircularLists := head;
end;
请注意,这个算法假设输入的两个链表都是升序的循环链表。