160. Intersection of Two Linked Lists

走远了吗. 提交于 2020-01-17 02:00:58
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int ALength = 0,BLength = 0;
        ListNode pA = headA;
        ListNode pB = headB;
        int move = 0;
        while(pA!=null)
        {
            ALength++;
            pA = pA.next;
        }
        while(pB!=null)
        {
            BLength++;
            pB = pB.next;
        }
        pA = headA;
        pB = headB;
        move = ALength>BLength ? ( ALength-BLength):(BLength-ALength);
        if(ALength>BLength)
        {
            while(move>0)
            {
                pA = pA.next;
                move--;
            }
        }
        else
        {
            while(move>0)
            {
                pB = pB.next;
                move--;
            }
        }

        while(pA!=null)
        {
            if(pA==pB)
                return pA;
            else
            {
                pA = pA.next;
                pB = pB.next;
            }
        }

        return null;

    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!