两个链表的联合 - C++

Union of two linked list- C++

本文关键字:C++ 链表 两个      更新时间:2023-10-16

任何帮助都会有所帮助。我写了一个代码来查找两个链表的并集。但是,我在一个部分得到了无限循环。我在代码中指出它。请帮助我识别错误。谢谢。

//Finds the union of two linked lists. 
nodeType* unionLL(nodeType *&headA, nodeType *&headB)
{
      nodeType *tempA, *tempB, *newNode;         
      tempA = headA;
      tempB = headB;
      bool match = false;
      while (tempB -> link != NULL)
      {
            while (tempA -> link != NULL)                
            {
                  outfile <<"The infinite loop occurs here " << endl;
                  if (tempB -> intVal == tempA -> intVal)
                  {   
                      match = true;
                  }  
                  tempA = tempA -> link;
            }
            if (!match)
            {
               newNode = new nodeType;
               newNode -> intVal = tempB -> intVal;
               newNode -> link = NULL;
               tempA -> link = newNode;
            }
            tempA = headB;
            tempB = tempB -> link;
      }
      return headB;
 }

您尚未确定链表是否排序 - 因此我们应该假设没有。 您尚未确定可以修改哪个列表;从表面上看,函数可以修改这两个列表。 您返回headB,这表明结果应该是可从headB访问的结果集应包含该列表中的每个元素,以及可从headA访问的尚未通过headB找到的每个元素的新元素。

从表面上看,你的伪代码应该是:

foreach element in listA
    if (element not found in listB)
        add copy of element to listB

留下列表 A 原封不动。 您的代码未实现此逻辑。

我认为您没有检查它是否在 tempA 循环中匹配(在 B 中也没有)