Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implementing Linked List Cycle in Python #467

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
33 changes: 33 additions & 0 deletions Python/Linked_List_Cycle.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#Time: 95.48%
#Space: 99.98%
#Difficulty: Easy
#Acceptance: 49.0%

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
# Return False if the list is empty or has only one node (no cycle possible)
if not head or not head.next:
return False

# Initialize two pointers: 'slow' moves one step at a time, 'fast' moves two steps
slow = head
fast = head.next

# Iterate through the list
while slow != fast:
# If 'fast' reaches the end of the list (or its next step is None), there's no cycle
if not fast or not fast.next:
return False

# Move 'slow' one step forward and 'fast' two steps forward
slow = slow.next
fast = fast.next.next

# If 'slow' and 'fast' meet, there is a cycle in the list
return True