【leetcode】求两个链表的交点

求两个链表的交点

c++
借助set

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        std::set<ListNode*>node_set;
        while(headA)
        {
            node_set.insert(headA);
            headA=headA->next;
        }
        while(headB)
        {
            if (node_set.find(headB)!=node_set.end())
                return headB;
            headB=headB->next;
        }
        return NULL;
    }
};

在这里插入图片描述

数学思维:

方法一

两人同时出发,相同的速度,先走自己的路,再走别人的路,走过的总路程一样,则一定会在交点处相遇,一起走向终点。
在这里插入图片描述

struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
    struct ListNode* PA=headA;
    struct ListNode* PB=headB;
    if (headA==NULL||headB==NULL)
       { 
           printf("aaaa");
            return NULL;
        }
    else{
            while(PA!=PB)
                {          
                    PA=PA==NULL?headB:PA->next;
                    PB=PB==NULL?headA:PB->next;
                }
                    return PA;
        }
}

在这里插入图片描述
方法二:
思路:
先把长链表多出来的节点去掉。
当两个链表的长度相同后,再开始以相同的速度分别遍历两个链表。
在这里插入图片描述

int get_list_length(ListNode *head){
    int list_len=0;
    while(head){
        list_len+=1;
        head=head->next;
    }
    return list_len;
}
ListNode* move(int long_length,int short_length,ListNode* head)
{
    int move_step=long_length-short_length;
    while(move_step&&head){
        head=head->next;
        move_step-=1;
    }
    return head;
}
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int lenA=get_list_length(headA);
        int lenB=get_list_length(headB);
        if (lenA>lenB){
            headA=move(lenA,lenB,headA);
        }
        else{
            headB=move(lenB,lenA,headB);
        }
        while(headA&&headB){
            if (headA!=headB){
                headA=headA->next;
                headB=headB->next;
            }
            else
                return headA;
        }
        return NULL;
    }
};

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值