相交链表(Java 常规方法+最简单方法)

本文探讨了两个单链表相交问题的两种解决方法,包括常规解法和一种更简洁的解法,通过巧妙地调整遍历策略,无需额外空间即可找出相交起始节点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

相交链表


题目

相交链表(力扣:160)

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

分析

常规解法:计算出两个链表的长度,然后算出长度差cha;让长度较长的链表先走cha步,这样就补齐了两个链表之间长度的差异,最后向后遍历,节点相等的地方即为解。

简单解法:该题最关键的是如何补齐两个链表之间的长度差。我们两个链表同时遍历,遍历结束时,让两个链表分别指向对方链表的头部,继续遍历,这样长度补齐了,当节点相等时,即为解。

代码实现:常规解法
    /**
     * 160. 相交链表
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA == null || headB == null){
            return null;
        }
        int l1 = 0, l2 = 0;
        ListNode curA = headA, curB = headB;
        while (curA != null){
            l1++;
            curA = curA.next;
        }
        while (curB != null){
            l2++;
            curB = curB.next;
        }
        int cha = Math.abs(l1 - l2);

        if (l1 >= l2){
            while (cha > 0){
                headA = headA.next;
                cha--;
            }
        }else {
            while (cha > 0){
                headB = headB.next;
                cha--;
            }
        }
        while (headA != null){
            if (headA == headB){
                return headA;
            }
            headA = headA.next;
            headB = headB.next;
        }
        return null;
    }
代码实现:简单解法
    /**
     * 160. 相交链表
     * @param headA
     * @param headB
     * @return
     */
    public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
        if (headA == null || headB == null){
            return null;
        }
        ListNode curA = headA, curB = headB;
        while (curA != curB){
            curA = curA == null ? headB : curA.next;
            curB = curB == null ? headA : curB.next;
        }
        return curA;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

卜大爷

觉得不错的可以给我加油哦

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值