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

2016-05-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;
    }
上一篇下一篇

猜你喜欢

热点阅读