LeetCode -- 推断链表中是否有环


思路:

使用两个节点。slow和fast,分别行进1步和2步。假设有相交的情况,slow和fast必定相遇;假设没有相交的情况,那么slow或fast必定有一个为null


相遇时有两种可能:
1. 仅仅是节点相交的情况,即:slow == fast可是 slow.next != fast.next
2. 链表中存在环,即slow == fast 并且 slow.next == next


实现代码:





public bool HasCycle(ListNode head) {
        // - for null node , false
        if(head == null || head.next == null){
            return false;
        }
        if(head.val != head.next.val && head.next.next == null){
            return false;
        }
        
        var slow = head; 
        var fast = head;


        while(true) {
            slow = slow.next;
            if(fast.next != null){
                fast = fast.next.next;
            }
            else{
                return false;
            }
            
            if(slow == null || slow.next == null || fast == null || fast.next == null) {
                return false;
            }
            
            if(slow.val == fast.val && slow.next.val == fast.next.val){
                return true;
            }
        }
        return false;
    }


原文地址:https://www.cnblogs.com/wzjhoutai/p/6741763.html