c - 如何在链表中获取两个集合的公共(public)元素?

标签 c

我有 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/

相关文章:

c - 如何将 void * 数据保存到头文件中?

C: 使用 "scanf"读取一行其他字符中的 float

iPhone SDK : Please explain why "nil ==" is different than "== nil"

c - Linux C 如何为 http 响应 block 动态分配内存?

c - C 语言的 FPGA 中断处理

c - 流错误指示器如何影响以下输入代码?

c++ - Cuda 内核返回 vector

c - 在将输入作为 shell 命令传递给 exe 时,可以将文件替换为缓冲区吗?

c - 段错误(核心转储)pthread

c - 使用 libpq 库将图像发送到 postgresql 数据库中的 bytea 列时出错