两个链表的并集 - 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;
}
Any assistance will be helpful. I have written a code to find the union of two linked list. However, I am getting an infinite loop at one section. I indicate it in the code. Please help me identify the error. Thanks.
//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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您还没有确定链接列表是否已排序 - 所以我们应该假设没有。您尚未确定可以修改哪些列表;从表面上看,两个列表都可以由该函数修改。您返回
headB
,这表明结果应该是可从headB
访问的结果集应包含该列表中的每个元素,以及可从可访问的每个元素的新元素>headA
尚未通过headB
找到。那么,从表面上看,您的伪代码应该是:
保持 listA 不变。您的代码没有实现此逻辑。
You have not identified whether the linked lists are sorted or not - so we should assume not. You have not identified which list can be modified; superficially, both lists could be modified by the function. You return
headB
which suggests that the result should be that the result set accessible fromheadB
should contain every element in that list, plus a new element for each element accessible fromheadA
that is not already found viaheadB
.Superficially, then, your pseudo-code should be:
leaving listA untouched. Your code does not implement this logic.
我认为你没有检查它是否在 tempA 循环中匹配(在 B 中也没有)
I think you are not checking if it matches in tempA loop (neither in B's)