Problem

Given a linked list, return the node where the cycle begins.

If there is no cycle, return null.

Example
Given -21->10->4->5, tail connects to node index 1,return 10

思路

  • slow pointer meeting fast pointer means it has cycle
  • when they meet each other, a pointer A starts moving forwards as the steps as slow pointer does. when they meet, it is the one
    public ListNode detectCycle(ListNode head) {  
        if (head == null) return head;

        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null && fast.next != null) {
            if (fast == slow) break;
            slow = slow.next;
            fast = fast.next.next;
        }

        if (fast != slow) return null;

        ListNode curt = head;
        while (curt != slow.next) {
            curt = curt.next;
            slow = slow.next;
        }
        return curt;
    }

results matching ""

    No results matching ""