LeetCode160. 相交链表之对的人即使错过也终会相逢

题目地址
编写一个程序,找到两个单链表相交的起始节点。

首先是常规解法:

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> set = new HashSet<>();
        while (headA!= null || headB != null){
            if (headA != null){
                if (set.contains(headA)){
                    return headA;
                }
                set.add(headA);
                headA = headA.next;
            }
            if (headB != null){
                if (set.contains(headB)){
                    return headB;
                }
                set.add(headB);
                headB = headB.next;
            }
        }
        return null;
    }

利用Set的特性,只要这个节点出现过就返回这个节点,即为交集。

第二种就是最浪漫的解法了:在这里插入图片描述
如果两个链表有交集,那么a + c + b + c = b + c + a + c,速度一致、走过的路程一致,那么肯定会有一段交集是肩并肩一起走下去的,此时a.next = b.next,如果不相交 a + b = b + a,你走你的阳关道,我过我的独木桥,虽然走过的路相同,但永远没有交集。

public class Solution {
    public ListNode getIntersectionNode(ListNode a, ListNode b) {
        if (a == null || b == null){
            return null;
        }
        ListNode aHead = a;
        ListNode bHead = b;
        while (a != b) {
        	//如果不相交,肯定同时到达“终点” 下一节点为null,跳出循环
            if (a.next == null && b.next == null){
                return null;
            }
            a = a.next == null ? bHead : a.next;
            b = b.next == null ? aHead : b.next;
        }
        return a;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值