美文网首页
LinkedList:2个单向链表找到第一个交点

LinkedList:2个单向链表找到第一个交点

作者: 敲一手烂代码 | 来源:发表于2016-05-20 14:20 被阅读48次
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
            if (headA==null||headB==null) {
                return null;
            }
            ListNode node1 = headA;
            ListNode node2 = headB;
            int headACount = 0;
            int headBCount = 0;
            while (node1.next!=null) {
                node1 = node1.next;
                ++headACount;
            }
            while (node2.next!=null) {
                node2 = node2.next;
                ++headBCount;
            }
            if (node1!=node2) {
                return null;
            }
            int step = headACount-headBCount;
            if (step>0) {
                while (step>0) {
                    headA = headA.next;
                    step--;
                }
            } else {
                step = -step;
                while (step>0) {
                    headB = headB.next;
                    step--;
                }
            }
            while (headA!=headB) {
                headA = headA.next;
                headB = headB.next;
            }
            return headA;
        }
    

    相关文章

      网友评论

          本文标题:LinkedList:2个单向链表找到第一个交点

          本文链接:https://www.haomeiwen.com/subject/cudnrttx.html