两个单向链表的第一个公共节点

问题:

两个单向链表,可能存在公共节点。如何判断是否存在公共节点,并找出它们的第一个公共结点。

思想:

1. 如果两个链表相交,则从相交点开始,后面的节点都相同,即最后一个节点肯定相同;
2. 从头到尾遍历两个链表,并记录链表长度,当二者的尾节点不同,则二者肯定不相交;
3. 尾节点相同,如果A长为LA,B为LB,如果LA>LB,则A前LA-LB个先跳过,
   然后二者一起向后遍历,直到遇到相同的节点;LA<LB类似处理
   因为第一个公共节点距起始节点的距离start_a满足: LA - start_a == LB - start_b。

简单代码:

const ListNode* FirstCommonNode(const ListNode* listA, const ListNode* listB)
{
    if(listA==NULL || listB==NULL) return NULL;
    int LA=1,LB=1;//A,B链表长度
    const ListNode* curA = listA, *curB = listB;
    while(curA->next)//求A尾节点
    {++LA; curA = curA->next;}
    while(curB->next)//求B尾节点
    {++LB; curB = curB->next;}
    if(curA != curB) return NULL;//尾节点不相同,则没有相交
    curA = listA;curB = listB;
    if(LA > LB)//
    {
        for(int i=0; i<LA-LB; ++i)
            curA = curA->next;
    }
    else
    {
        for(int i=0; i<LB-LA; ++i)
            curB = curB->next;
    }
    while(curA && curA!=curB)
    {
        curA = curA->next;
        curB = curB->next;
    }
    return curA;
}

简单测试代码:

void CreateJointList(const string* strA, int sizeA,const string* strB ,int sizeB,
    const string* strC,int sizeC,ListNode** listA,ListNode** listB)//创建两个相交的链表
{
    ListNode* rootA = new ListNode(strA[0]);
    ListNode* rootB = new ListNode(strB[0]);
    *listA = rootA; *listB = rootB;
    for(int i=1; i<sizeA; ++i)
    {
        rootA->next = new ListNode(strA[i]);
        rootA = rootA->next;
    }
    for(int i=1; i<sizeB; ++i)
    {
        rootB->next = new ListNode(strB[i]);
        rootB = rootB->next;
    }
    ListNode* tmp = new ListNode(strC[0]);
    rootA->next = tmp;
    rootB->next = tmp;
    for(int i=1; i<sizeC; ++i)
    {
        tmp->next = new ListNode(strC[i]);
        tmp = tmp->next;
    }
}

    ListNode *headA,*headB;
    const int SizeA = 6,SizeB = 7,SizeC = 5;
    const string A[SizeA] = {"I","am","an","List","named","A"};
    const string B[SizeB] = {"I","am","also","an","List","named","B"};
    const string C[SizeC] = {"this","part","is","in","Comman"};
    CreateJointList(A,SizeA,B,SizeB,C,SizeC,&headA,&headB);
    PrintList(headA);
    PrintList(headB);
    const ListNode *node = FirstCommonNode(headA, headB);

    if(node != NULL)
        cout<<"\nCommon Node : \t"<<node->value<<endl;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值