1. 程式人生 > >劍指offer——(10)兩個連結串列的第一個公共結點

劍指offer——(10)兩個連結串列的第一個公共結點

圖解: 

程式碼: 

public class Solution {
/*
    遍歷兩條連結串列得到各自的長度,長的先next兩條連結串列的長度差,然
    後一起走next,如果有公共結點,此結點及之後的連結串列值都相同。
*/
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if(pHead1==null||pHead2==null) return null;        
        ListNode pre1 = pHead1,pre2 = pHead2;
        while(pre1!=null){
           length1++;
           pre1 = pre1.next;
        }
        while(pre2!=null){
            length2++;
            pre2 = pre2.next;
        }
        if(length1>=length2) {
            for(int i=1;i<=length1-length2;i++){
                pHead1 = pHead1.next;
            }
        }
        else{
            for(int i=1;i<=length2-length1;i++)
                pHead2 = pHead2.next;           
        }
        while(pHead1!=pHead2){
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;  
        }
        return pHead1;     
    }
}

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/