160. Intersection of Two Linked Lists

/**
 * 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;

    }
}
160. Intersection of Two Linked Lists160. Intersection of Two Linked Lists Haha@25 发布了32 篇原创文章 · 获赞 2 · 访问量 2103 私信 关注
上一篇:LeetCode 160. 相交链表 (找出两个链表的公共结点)


下一篇:160 找出两个链表的交点