PU Linked List Cycle II

Jan 01, 1970

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

  • Do not modify the linked list.
  • Can you solve it without using extra space?

C Solution:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *slow = head, *fast = head;
    while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) break;
    }
    if (!fast || !fast->next) return 0;
    while (head != fast) {
        head = head->next;
        fast = fast->next;
    }
    return head;
}

Python Solution:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def detectCycle(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head: return
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast: break
        if not fast or not fast.next: return
        while head != slow:
            head = head.next
            slow = slow.next
        return head

Summary:

  1. 6ms, 29.87%
  2. When you know the logic, there is nothing special.

LeetCode: 142. Linked List Cycle II