Skip to content

Instantly share code, notes, and snippets.

@drem-darios
Created February 10, 2020 06:51
Show Gist options
  • Save drem-darios/3bc3f9d554d86e7c3da951bc5a14fe35 to your computer and use it in GitHub Desktop.
Save drem-darios/3bc3f9d554d86e7c3da951bc5a14fe35 to your computer and use it in GitHub Desktop.
Given the head of a Singly LinkedList, write a function to determine if the LinkedList has a cycle in it or not.
class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def has_cycle(head):
fast_pointer = head
slow_pointer = head
while fast_pointer is not None and fast_pointer.next is not None:
fast_pointer = fast_pointer.next.next
slow_pointer = slow_pointer.next
if fast_pointer == slow_pointer:
return True
return False
def main():
head = Node(1)
head.next = Node(2)
head.next.next = Node(3)
head.next.next.next = Node(4)
head.next.next.next.next = Node(5)
head.next.next.next.next.next = Node(6)
print("LinkedList has cycle: " + str(has_cycle(head)))
head.next.next.next.next.next.next = head.next.next
print("LinkedList has cycle: " + str(has_cycle(head)))
head.next.next.next.next.next.next = head.next.next.next
print("LinkedList has cycle: " + str(has_cycle(head)))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment