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

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int nLength1 = GetListLen(headA);
        int nLength2 = GetListLen(headB);
        int nLengthDif = nLength1 - nLength2;

        ListNode pListHeadLong = headA;
        ListNode pListHeadShort =headB;

        if(nLength2 > nLength1){
            pListHeadLong = headB ;
            pListHeadShort = headA ;
            nLengthDif = nLength2 - nLength1;
        }
        //长的先走
        for(int i=0;i<nLengthDif;i++){
            pListHeadLong = pListHeadLong.next;
        }
        while((pListHeadLong!=null)&& (pListHeadShort!=null)&& (pListHeadShort != pListHeadLong)){
            pListHeadLong = pListHeadLong.next;
            pListHeadShort = pListHeadShort.next;
        }
        //得到公共节点
        ListNode pListHeadCommonNode = pListHeadLong;
        return pListHeadCommonNode;
    }


    //计算链表的长度
    int GetListLen(ListNode pHead){
        int nlen = 0;
        ListNode pNode = pHead;
        while(pNode!= null){
            nlen++;
            pNode = pNode.next;
        }
        return nlen;
    }
}

剑指offer上 大神 腐烂的橘子 的题解,感动了众多刷题狗,没想到刷题也这么浪漫

原文地址:https://www.cnblogs.com/peanut-zh/p/14146686.html