LinkedList:输入两个链表,找出它们的第一个公共结点。

public static ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1==null||pHead2==null) {
            return null;
        }
        if (!isLoop(pHead1) && !isLoop(pHead2)) {
            return getIntersectionNode(pHead1, pHead2);
            
        }
        if (isLoop(pHead1) && isLoop(pHead2)) {
            ListNode loopNode1 = getLoopNode(pHead1);
            ListNode loopNode2 = getLoopNode(pHead2);
            if (loopNode1==loopNode2) {
                return getIntersectionNode(pHead1, pHead2);
            }
            ListNode cur = loopNode1.next;
            while (cur!=loopNode2) {
                if (cur==loopNode1) {
                    return null;
                }
                cur = cur.next;
            }
            return cur;
        }
        return null;
    }
    
    public static ListNode getIntersectionNode(ListNode pHead1,ListNode pHead2) {
        ListNode node1 = pHead1;
        int nodeCount1 = 0;
        ListNode node2 = pHead2;
        int nodeCount2 = 0;
        while (node1.next!=null) {
            nodeCount1++;
            node1 = node1.next;
        }
        while (node2.next!=null) {
            nodeCount2++;
            node2 = node2.next;
        }
        if (node1!=node2) {
            return null;
        }
        int step = nodeCount1-nodeCount2;
        if (step>0) {
            while (step>0) {
                step--;
                pHead1 = pHead1.next;
            }
        } else {
            step = -step;
            while (step>0) {
                step--;
                pHead2 = pHead2.next;
            }
        }
        while (pHead1!=pHead2) {
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return pHead1;
    }
    
    public static boolean isLoop(ListNode node) {
        if (node==null) {
            return false;
        }
        if (node.next==null||node.next.next==null) {
            return false;
        }
        ListNode fast = node.next.next;
        ListNode slow = node.next;
        while (fast.next!=null&&fast.next.next!=null) {
            if (fast==slow) {
                return true;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return false;
    }
    
    public static ListNode getLoopNode(ListNode node) {
        ListNode fast = node.next.next;
        ListNode slow = node.next;
        while (fast!=slow) {
            fast = fast.next.next;
            slow = slow.next;
        }
        fast = node;
        while (fast!=slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容