判断两个不带环的链表是否相交,若相交,求交点。

问题描述:

判断两个不带环的链表是否相交,若相交,求交点。

1、判断是否相交
思路:分别遍历两个链表,比较两个链表的最后一个节点是否相等,如果相等,则相交,如果不相等,则不相交。
2、代码实现如下:

bool IsListIntersection(pSListNode pHead1, pSListNode pHead2)
{
    pSListNode cur1 = pHead1;
    pSListNode cur2 = pHead2;
    if (pHead1 == NULL || pHead2 == NULL)
        return false;
    while (cur1->_next)
        cur1 = cur1->_next;
    while (cur2->_next)
        cur2 = cur2->_next;
    if (cur1 == cur2)
        return true;
    else
        return false;
}

3、求两个相交链表的交点:
方法一:先遍历一个链表,找到尾节点,将尾节点的next指向第二个链表的头结点,构造成一个带环的链表,求环的入口点;
代码实现如下:

pSListNode GetIntersectionPoint1(pSListNode pHead1, pSListNode pHead2)
{
    pSListNode tail = pHead1;
    pSListNode Fast = pHead1;
    pSListNode slow = pHead1;
    pSListNode cur = pHead1;
    if (pHead1 == NULL || pHead2 == NULL)
        return NULL;
    while (tail->_next)
        tail = tail->_next;
    tail->_next = pHead2;
    while (Fast&&Fast->_next)
    {
        slow = slow->_next;
        Fast = Fast->_next->_next;
        if (Fast == slow)
            break;
    }
    while (Fast != cur)
    {
        cur = cur->_next;
        Fast = Fast->_next;
    }
    return cur;
}

方法二:
实现思路:分别遍历两个链表,统计每一个链表的长度,设两个链表的长度差为n,让指向长的链表的指针先走n步,然后两个链表的指针同时一起走,当两个指针相遇时,则该节点就是他们的交点;
具体代码实现如下:

pSListNode GetIntersectionPoint2(pSListNode pHead1, pSListNode pHead2)
{
    pSListNode cur1 = pHead1;
    pSListNode cur2 = pHead2;
    pSListNode tmp1 = pHead1;
    pSListNode tmp2 = pHead2;
    int num = 0;
    int len1 = 0;
    int len2 = 0;
    while (cur1)
    {
        len1++;
        cur1 = cur1->_next;
    }
    while (cur2)
    {
        len2++;
        cur2 = cur2->_next;
    }
    if (len1 >= len2)
    {
        num = len1 - len2;
        while (num--)
        {
            tmp1 = tmp1->_next;
        }
        while (tmp1 != tmp2)
        {
            tmp1 = tmp1->_next;
            tmp2 = tmp2->_next;
        }
        return tmp1;
    }
    else
    {
        num = len2 - len1;
        while (num--)
        {
            tmp2 = tmp2->_next;
        }
        while (tmp1 != tmp2)
        {
            tmp1 = tmp1->_next;
            tmp2 = tmp2->_next;
        }
        return tmp2;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值