剑指 Offer 52. 两个链表的第一个公共节点

输入两个链表,找出它们的第一个公共节点。

如下面的这个链表:

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。


public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lena = len(headA);
        int lenb = len(headB);
        while(lena >lenb){            //a长 A先走
            headA = headA.next;
            lena--;
        }

        while(lenb >lena){            //b长 B先走
            headB = headB.next;
            lenb--;
        }
        
        while(headA != headB){        //然后再一起走,一定会相遇
            headA = headA.next;
            headB = headB.next;
            
        }
        return headA;

    }
    public int len(ListNode L){
        int count = 0;

        while(L != null){
            L = L.next;
            count++;
        }
        return count;
    }
}
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        ListNode n1 = headA;
        ListNode n2 = headB;
        
        while(n1 != n2){
            n1 = n1 == null ? headB : n1.next;    //谁为空,那就从另一个链表的头开始走
            n2 = n2 == null ? headA : n2.next;
        }
        return n1;
    }
}
posted @ 2021-01-05 08:34  xiaoff  阅读(79)  评论(0编辑  收藏  举报