簡體   English   中英

兩個鏈表的並集 - C++

[英]Union of two linked list- C++

任何幫助都會有所幫助。 我寫了一個代碼來查找兩個鏈表的並集。 但是,我在一個部分得到一個無限循環。 我在代碼中指出。 請幫我找出錯誤。 謝謝。

//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;
 }

您尚未確定鏈接列表是否已排序 - 所以我們應該假設沒有。 您尚未確定可以修改哪個列表; 從表面上看,這兩個列表都可以被 function 修改。 您返回headB ,這表明結果應該是從headB可訪問的結果集應該包含該列表中的每個元素,加上尚未通過headB找到的從headA可訪問的每個元素的新元素。

那么,從表面上看,您的偽代碼應該是:

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

保持 listA 不變。 您的代碼未實現此邏輯。

我認為您沒有檢查它是否在 tempA 循環中匹配(不在 B 中)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM