我有 2 个链表,我想比较两个列表并打印出现在两个列表中的每个公共(public)元素。尝试了一切都无法正常工作。
struct Node *calcIntersection(struct Node *headA, struct Node *headB)
{
struct Node * link1 = headA;
struct Node * link2 = headB;
while(link1 != NULL)
{
if (link2->value == link2->value)
{
printf("%d", link1->value);
}
link1 = link1 -> pNext;
}
return link1;
}
最佳答案
你很接近,实际上你的方法应该是这样的:
struct Node *calcIntersection(struct Node *headA, struct Node *headB)
{
struct Node *link1 = headA;
while(link1 != NULL)
{
struct Node *link2 = headB;
while (link2 != NULL)
{
if (link1->value == link2->value)
{
printf("%d", link1->value);
}
link2 = link2->pNext;
}
link1 = link1->pNext;
}
return link1;
}
我不太确定你在那里返回什么,但在大多数情况下你将返回 NULL,但我不太确定这是否是你想要的。
关于c - 如何在链表中获取两个集合的公共(public)元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9814647/