Skip to content

Instantly share code, notes, and snippets.

@wanderindev
Created July 9, 2022 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wanderindev/5d64c13ab8eeca0f85dc5931be5e3366 to your computer and use it in GitHub Desktop.
Save wanderindev/5d64c13ab8eeca0f85dc5931be5e3366 to your computer and use it in GitHub Desktop.
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