Skip to content
This repository was archived by the owner on Sep 22, 2021. It is now read-only.
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions LeetCode/0141_Linked_List_Cycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
'''
Solution using Floyd's cycle-finding algorithm (tortoise and hare)
'''

def hasCycle(self, head: ListNode) -> bool:
if not head or not head.next:
return False

fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next

# If there is a cycle, fast will inevitably be on the same node as
# slow.
if fast is slow:
return True
return False


class SolutionO1:
'''
Solution to follow up. Disregards contents of each ListNode.
'''

def hasCycle(self, head: ListNode) -> bool:
while head:
if head.val is None:
return True
head.val = None
head = head.next
return False