160. Intersection of Two Linked Lists 寻找两个链表的焦点

读完题,第一时间想到的办法就是交织前进两个指针,不断判断是否找到合理的焦点。但是,后来发现这个方法不可取。因为,交织前进忽略了长度不等时,许多的判断问题。查阅大人解法后,发现可行的方案是:

A,先把问题转化为计算长度的问题,遍历两个链表。

B,利用A的结果,可以先回答是否存在焦点这个问题,然后,可以知道两个链表的距离差。

C,利用距离差,将两个链表推倒同距离位点,这样就可以同步比较了。

D,同步推进比较。

在思考过程中,曾经想过使用()?():()这个表达式,但是后来推翻了,不过如果以后有机会在获取差值时,不想引用math.abs,确实值得使用。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null || headB == null) return null;
        ListNode indexA = headA;
        ListNode indexB = headB;
        int countA = 1;
        int countB = 1;
        while (indexA.next != null)
        {
            countA++;
            indexA = indexA.next;
        }
        while (indexB.next != null)
        {
            countB++;
            indexB = indexB.next;
        }
        if (indexA != indexB) return null;
        indexA = headA;
        indexB = headB;
        if(countA > countB)
        {
            while((countA - countB) != 0)
            {
                indexA = indexA.next;
                countA--;
            }
        }
        else
        {
            while((countB - countA) != 0)
            {
                indexB = indexB.next;
                countB--;
            }
        }
        while(indexA != indexB)
        {
            indexA = indexA.next;
            indexB = indexB.next;
        }
        return indexA;
    }
}

 

posted @ 2016-04-12 09:24  ProWhalen  阅读(344)  评论(0)    收藏  举报