Detect Cycle in a Linked List
Given head, the head of a linked list, determine if the linked list has a cycle in it. Tags: Linked List
Try It!
Discussion
Video
Solution
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
fast = head
slow = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
if fast == slow:
return True
return False