2018-08-21 LeetCode 相交链表(无环)

双指针,p指针先遍历A再遍历B,q指针先遍历B再遍历A,如果相交则一定会有p==q

public class Solution {  
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {  
        if(headA==null || headB==null) return null;        
        ListNode p = headA;  
        ListNode q = headB;  
        if(p == q) return p;          
        while(p!=null && q!=null) {  
            p = p.next;  
            q = q.next;  
        }     
        if(p==null) p = headB; else q = headA;   
        while(p!=null && q!=null) {  
            p = p.next;  
            q = q.next;  
        }  
        if(p==null) p = headB; else q = headA;  
        while(p!=null && q!=null) {  
            if(p==q) return p;  
            p = p.next;  
            q = q.next;  
        }  
        return null;  
    }  
}  

你可能感兴趣的:(2018-08-21 LeetCode 相交链表(无环))