-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Day 12: Attempt 2: 141_Linked_List_Cycle
- Loading branch information
Showing
2 changed files
with
18 additions
and
0 deletions.
There are no files selected for viewing
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
17 changes: 17 additions & 0 deletions
17
top_interview_questions/75_hard/Linked List/141_Linked_List_Cycle.py
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
from typing import Optional | ||
# 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: | ||
tortoise = head | ||
hare = head | ||
while hare and hare.next: | ||
tortoise = tortoise.next | ||
hare = hare.next.next | ||
if tortoise == hare: | ||
return True | ||
return False |