面试题 02.07. 链表相交

链表对齐之后再判断

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        // 首先计算两个链表的长度,然后让两个链表向右对齐,然后从左到右判断
        int n1 = 0, n2 = 0;
        for (ListNode p = headA; p != null; p = p.next) {
            n1++;
        }
        for (ListNode p = headB; p != null; p = p.next) {
            n2++;
        }
        ListNode shortNode, LongNode;
        int dif;
        if (n1 > n2) {
            dif = n1 - n2;
            shortNode = headB;
            LongNode = headA;
        } else {
            dif = n2 - n1;
            shortNode = headA;
            LongNode = headB;
        }
        for (int i = 0; i < dif; i++) {
            LongNode = LongNode.next;
        }
        // 开始比较
        while (shortNode != null) {
            if (shortNode == LongNode) {
                return shortNode;
            }
            shortNode = shortNode.next;
            LongNode = LongNode.next;
        }
        return null;
    }
}

牛逼解法

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode h1 = headA, h2 = headB;
        //如果不相交就会在转完两个链表之后指向空
        while (h1 != h2) {
        	//当两个链表长度不一致时,h1和h2不会同时为空
            //h1是空说明a+c已经遍历完,应该换向b
            //如果有交集,h1和h2会同时到达c的开头
            //如果没有交集,h1和h2会同时指向空
            h1 = (h1 == null) ? headB : h1.next;
            h2 = (h2 == null) ? headA : h2.next;
        }
        return h1;
    }
}
设交集链表长c,链表1除交集的长度为a,链表2除交集的长度为b,有		
	- a + c + b = b + c + a
	 - 若无交集,则a + b = b + a
  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值