Skip to content

Instantly share code, notes, and snippets.

@Per48edjes
Created November 30, 2022 02:32
Show Gist options
  • Save Per48edjes/e9329d05085e321c37f38579b6629ee2 to your computer and use it in GitHub Desktop.
Save Per48edjes/e9329d05085e321c37f38579b6629ee2 to your computer and use it in GitHub Desktop.
LeetCode 141. Linked List Cycle
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
@Per48edjes
Copy link
Author

This is partial implementation of Floyd's "Tortoise and Hare" algorithm, which in full, calculates the cycle length if a cycle is present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment