相交链表

方法一: 暴力法  遍历A中每个节点,看看B中有没有

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if (headA==null||headB==null) return null;

        while(headA!=null){
            ListNode nodeB=headB;
            while(nodeB!=null){
            
            if(headA==nodeB){
                return nodeB;
            }else{
              nodeB=nodeB.next;
            }
            }
            headA=headA.next;
        } 
       return null; 
    }
}

方法二:可以理解成两个人速度一致, 走过的路程一致。那么肯定会同一个时间点到达终点。如果到达终点的最后一段路两人都走的话,那么这段路上俩人肯定是肩并肩手牵手的

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;
}

  

原文地址:https://www.cnblogs.com/focusonoutput/p/13515555.html