-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path142-linked-list-cycle-II.py
More file actions
45 lines (37 loc) · 1.14 KB
/
142-linked-list-cycle-II.py
File metadata and controls
45 lines (37 loc) · 1.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
# if head == None or head.next == None:
# return None
# slow,fast = head,head
# while fast and fast.next:
# slow = slow.next
# fast = fast.next.next
# if slow == fast:
# break
# if slow == fast:
# slow = head
# while slow != fast:
# slow = slow.next
# fast = fast.next
# return slow
# return None
if head == None or head.next == None:
return None
slow=fast=head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
if slow == fast:
slow = head
while fast != slow:
slow = slow.next
fast = fast.next
return slow
#return None