leetpycode/easy/linked_list_cycle.py

23 lines
562 B
Python

# https://leetcode.com/problems/linked-list-cycle
from typing import Optional
class ListNode:
val: int
next: Optional["ListNode"]
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
first: Optional[ListNode] = head
second: Optional[ListNode] = head
while first is not None and \
first.next is not None and \
second is not None:
first = first.next.next
second = second.next
if first == second:
return True
return False