-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinked List Cycle II.py
More file actions
36 lines (31 loc) · 868 Bytes
/
Linked List Cycle II.py
File metadata and controls
36 lines (31 loc) · 868 Bytes
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
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def detectCycle(self, head):
fast = head
slow = head
encounter = None
while fast is not None and fast.next is not None:
fast = fast.next.next
slow = slow.next
if fast is slow:
encounter = fast
break
if encounter is None:
return None
else:
while head is not encounter:
head = head.next
encounter = encounter.next
return head
head = ListNode(1)
head.next = ListNode(2)
head.next.next = ListNode(3)
head.next.next.next = head.next
result = Solution()
print result.detectCycle(head)