其他分享
首页 > 其他分享> > 160. Intersection of Two Linked Lists

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;

    }
}
Haha@25 发布了32 篇原创文章 · 获赞 2 · 访问量 2103 私信 关注

标签:ListNode,move,Two,next,pB,pA,Intersection,160,ALength
来源: https://blog.csdn.net/qq_37637619/article/details/104006865