C# two phases solution, easy to understand


  • 0
    H

    public class Solution {

    public ListNode DetectCycle(ListNode head) {
        ListNode slow = head;
        ListNode fast = head;
        bool flag = false;
        
        // Detect if cycle exists
        while( fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            
            if( slow == fast){ 
                flag = true; 
                break;
            }
        }
        
        if( !flag) return null;
        
        // Find beginning code of the cycle
        fast = head;
        while ( fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        
        return slow;
        
    }
    

    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.