Created
November 30, 2022 02:32
-
-
Save Per48edjes/e9329d05085e321c37f38579b6629ee2 to your computer and use it in GitHub Desktop.
LeetCode 141. Linked List Cycle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from typing import Optional | |
class ListNode: | |
def __init__(self, val, next=None): | |
self.val = val | |
self.next = next | |
def hasCycle(head: Optional[ListNode]) -> bool: | |
""" | |
LeetCode 141. Link List Cycle | |
""" | |
tortoise = hare = head | |
while hare and hare.next: | |
tortoise = tortoise.next | |
hare = hare.next.next | |
if tortoise is hare: | |
return True | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is partial implementation of Floyd's "Tortoise and Hare" algorithm, which in full, calculates the cycle length if a cycle is present.