#include<iostream>
using namespace std;
#include<set>
struct node
{
node(int value = 0):v(value){}
int v;
node *next;
};
node *find(node *heada,node *headb)
{
set<node*> ss;
while(heada)
{
ss.insert(heada);
heada = heada->next;
}
while(headb)
{
if(ss.find(headb) != ss.end())
return headb;
headb = headb->next;
}
return NULL;
}
void main()//测试数据
{
node a1(1);
node a2(2);
node b1(0);
node b2(4);
node b3(5);
node c1(9);
node c2(8);
node *heada = &a1;
a1.next = &a2;
a2.next = &c1;
c1.next = &c2;
node *headb = &b1;
b1.next = &b2;
b2.next = &b3;
b3.next = &c1;
c2.next = NULL;
cout<<find(heada,headb)->v<<endl;
}
本文介绍了一种使用集合数据结构查找两个链表交集节点的算法实现,通过遍历第一个链表并将节点地址存入集合,再遍历第二个链表检查节点是否存在于集合中,从而找到第一个公共节点。示例代码展示了如何创建链表并调用查找函数,验证算法的有效性。
723

被折叠的 条评论
为什么被折叠?



