Created
July 9, 2022 22:21
-
-
Save wanderindev/5d64c13ab8eeca0f85dc5931be5e3366 to your computer and use it in GitHub Desktop.
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
class ListNode(object): | |
def __init__(self, x): | |
self.val = x | |
self.next = None | |
class Solution(object): | |
def has_cycle(self, head): | |
""" | |
:type head: ListNode | |
:rtype: bool | |
""" | |
slow_pointer = head | |
fast_pointer = head | |
while fast_pointer and fast_pointer.next: | |
slow_pointer = slow_pointer.next | |
fast_pointer = fast_pointer.next.next | |
if slow_pointer == fast_pointer: | |
return True | |
return False | |
# Test cases | |
sol = Solution() | |
ll = ListNode(3) | |
ll.next = ListNode(2) | |
ll.next.next = ListNode(0) | |
ll.next.next.next = ListNode(-4) | |
ll.next.next.next.next = ll.next | |
assert sol.has_cycle(ll) | |
ll = ListNode(1) | |
ll.next = ListNode(2) | |
ll.next.next = ll.next | |
assert sol.has_cycle(ll) | |
ll = ListNode(1) | |
assert not sol.has_cycle(ll) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment