求两个链表的交点并输出交点所带的值

本文介绍了一种使用集合数据结构查找两个链表交集节点的算法实现,通过遍历第一个链表并将节点地址存入集合,再遍历第二个链表检查节点是否存在于集合中,从而找到第一个公共节点。示例代码展示了如何创建链表并调用查找函数,验证算法的有效性。

#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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值