(160)-(Intersection of Two Linked Lists)-(尾巴相同的list)-(不仅仅是求交集,理解题目的意思很重要)

(160)-(Intersection of Two Linked Lists)-(尾巴相同的list)-(不仅仅是求交集,理解题目的意思很重要)

public class Solution
{
    public ListNode getIntersectionNode(ListNode headA, ListNode headB)
    {
        
        if(headA==null||headB==null)
        {
            //因为求的是交集
            return null; 
        }
        
        ListNode final_ans=headA;
        ListNode tail_ans=headA;
        
        ListNode moveA=headA;
        ListNode moveB=headB;
        
        int a_len=0;
        int a_tail=0;
        while(moveA!=null)
        {
            a_len++;
            a_tail=moveA.val;
            tail_ans=moveA;
            moveA=moveA.next;
        }
        
        int b_len=0;
        int b_tail=0;
        while(moveB!=null)
        {
            b_len++;
            b_tail=moveB.val;
            
            moveB=moveB.next;
        }
        //如果连尾巴都不一样,那么肯定么有交集了
        if(a_tail!=b_tail)
        {
            return null; 
        }
        //让长的那个先走,直到两个一样长
        int com_len =Math.min(a_len, b_len);
        for(int i=0;i<a_len-com_len;i++)
        {
            headA=headA.next;
        }
        for(int i=0;i<b_len-com_len;i++)
        {
            headB=headB.next;
        }
        
        int flag=0;
        
        for(int i=0;i<com_len;i++)
        {
            if(headA.val!=headB.val)
            {
                headA=headA.next;
                headB=headB.next;
                flag=0; //之后遇到的仍然算是第一次
                continue;
            }
            //如果兩者相等
            else
            {
                if(flag==0)
                {
                    //第一次相等
                    final_ans=headA;  
                    flag=1;  //之后就不是第一次了
                }    
            }
        }
        return final_ans;
    }

    
}

 

posted @ 2015-07-25 20:06  爱吃萝卜干  阅读(97)  评论(0编辑  收藏  举报