LinkedList:两个单链表,返回第一个相交点,假设2个单链表都没有环

public Node getIntersectionNode(Node headA, Node headB) {
        if (headA==null||headB==null) {
            return null;
        }
        Node node1 = headA;
        Node 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个单链表都没有环)