两链表第一个公共节点

题目:输入两个链表,找出它们的第一个公共结点。

思路:先求两个链表的长度,求长度差n,让长的那个链表先走n,两个链表再同时走,直到指针指到相同节点。

更简洁的答案:(实际上时间复杂度并没有减少,遍历的次数也没有减少,只是答案简洁)

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    if (headA == null || headB == null) return null;
    ListNode pA = headA, pB = headB;
    while (pA != pB) {
        pA = pA == null ? headB : pA.next;
        pB = pB == null ? headA : pB.next;
    }
    return pA;
}

作者:user7208t
链接:https://leetcode-cn.com/problems/two-sum/solution/tu-jie-xiang-jiao-lian-biao-by-user7208t/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
 public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null) return null;
             int n=0,m=0,cha=0;
        ListNode r1=pHead1,r2=pHead2;
        while(r1!=null){
            n++;
            r1=r1.next;
        }
        
        while(r2!=null){
            m++;
            r2=r2.next;
        }
        if(n>=m){
            cha=n-m;
            while(cha-->0){
                pHead1=pHead1.next;
            }
            while(pHead1!=pHead2){
                pHead1=pHead1.next;
                pHead2=pHead2.next;
            }
           
        }else{
            cha=m-n;
            while(cha-->0){
                pHead2=pHead2.next;
            }
            while(pHead1!=pHead2){
                pHead1=pHead1.next;
                pHead2=pHead2.next;
            }
        }
        return pHead1;
    }
原文地址:https://www.cnblogs.com/team42/p/6684987.html