My neat code to solve it with explanation in the picture(C++)


  • 3
    P
    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            ListNode *fast = head;
    		ListNode *slow = head;
    		ListNode *entry = head;
    		if(!head || !head->next) return NULL;
    		while(fast->next && fast->next->next) {
    			fast = fast->next->next;
    			slow = slow->next;
    			if(fast == slow) {
    				while(entry != slow) {
    					entry = entry->next;
    					slow = slow->next;
    				}
    				return entry;
    			}
    		}
    		return NULL;
        }
    };
    

    enter image description here


Log in to reply
 

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