2011-05-23 92 views
2

任何帮助都将有所帮助。我写了一个代码来查找两个链表的联合。但是,我正在一个部分获得无限循环。我在代码中指出它。请帮我找出错误。谢谢。两个链接列表的联合 - 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; 
} 
+0

把它们放入std :: set怎么样? – xDD 2011-05-23 23:36:47

+0

如果这是一个家庭作业问题,请阅读http://meta.stackexchange.com/questions/10811/how-to-ask-and-answer-homework-questions – MatrixFrog 2011-05-23 23:36:47

+2

评论:'' - >''操作符绑定非常严格的逻辑;不要在代码两边都写空格......对于有经验的程序员来说看起来很奇怪。 – 2011-05-23 23:42:34

回答

4

您还没有确定链表是否已排序 - 所以我们不应该假设。您尚未确定哪些列表可以修改;从表面上看,这两个列表都可以被该函数修改。您返回headB,这表明结果应该是可从headB访问的结果集应该包含该列表中的每个元素,并且还可以为从headA访问的每个元素添加一个新元素,该元素尚未通过headB找到。

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

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

留下原封不动listA的。你的代码没有实现这个逻辑。

+0

非常感谢。我将再次处理我的代码,并使用您提供给我的伪代码对其进行重构。这真的很有帮助。谢谢。 – ck22 2011-05-24 04:58:32

0

我想你不检查它是否匹配tempA循环(在B的都没有)