如何在帕斯卡中比较两个线性列表



任务是创建包含 2 个线性列表的新列表,如果第一个列表的元素等于第二个列表的元素,那么我们必须从新列表中删除相同的元素

 procedure CreateList(var t1,L1,t2,L2:plist);
 var 
 tmp1, tmp2:plist;
 begin
  t1 := L1;
  t2 := L2;
  while t1 <> nil do
  begin
  write(t1^.Data, ' ');
  t1 := t1^.Next;

  while t2 <> nil do
  begin
  write(t2^.data, '  ');
  tmp2:=t2;
  t2 := t2^.Next;
   if(t2 = tmp1^.next) then // here is the problem how to compare 2 elements
   begin
   tmp1 := t1; 
   t1 := t1^.Next;
   Dispose(tmp1); 
   end;
end; 
end;
Writeln;
readkey;
end;

我建议您更改列表的类型,例如:

type
  TData = integer;
  PList = ^TList;
  TList = record
    data : TData;
    next : PList;
    copy : boolean;
  end;

之后,您将使用值 .copy 检查副本。这是您需要的简单代码。我试图使所有代码尽可能简单。

procedure deleteCopys(var list:PList);
// make all TList.copy := false (after we will use it)
var
  curList : PList;
begin
  curList := list;
  while (curList<>nil) do
  begin
    curList^.copy := false;
    curList := curList^.next;
  End;
End;
procedure createList(var list1, list2, list3:PList);
// we belive that: (list3 is empty) and (there is no copys in list1)
//                 and (there is no copys in list2)
var
  curList1, curList2 : PList;
begin
  deleteCopys(list1);
  deleteCopys(list2);
  deleteCopys(list3);
  // make TList.copy := true for equal elements 
  // from curList1 and curList2
  curList1 := list1;
  while (curList1 <> nil) do
  begin
    curList2 := list2;
    while (curList2 <> nil) do
    begin
      if (curList1^.data = curList2^.data) then
      begin
        curList1^.copy := true;
        curList2^.copy := true;
        break;
      End;
      curList2 := curList2^.next;
    End;
    curList1 := curList1^.next;
  End;
  // now we can put all elements from list1 and list2 
  // with state TLilt.copy=false
  // and each of them will be different
  // (Let's do it :)
  curList1 := list1;
  while (curList1 <> nil) do
  begin
    if (curList1^.copy = false) then
    begin
      //some procedure for new element
      putNewElement(list3, curList1^.data);
    End;
  End;
  curList2 := list2;
  while (curList2 <> nil) do
  begin
    if (curList2^.copy = false) then
    begin
      //some procedure for new element
      putNewElement(list3, curList2^.data);
    End;
  End;
end;

希望对您有所帮助!

相关内容

  • 没有找到相关文章

最新更新