142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note:
Do not modify the linked list.
Follow-Up:
Can you solve it without using extra space?
Solution: Two Pointers
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return None
slow = head
fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
slow = head
break
while fast and fast != slow:
fast = fast.next
slow = slow.next
return fast