-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlinked_list_cycle_2.py
59 lines (46 loc) · 1.03 KB
/
linked_list_cycle_2.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#
# https://leetcode.com/problems/linked-list-cycle-ii/
#
# Given linked list find a node where cycle started
#
# Classical Floyd approach: https://en.wikipedia.org/wiki/Cycle_detection#Floyd's_Tortoise_and_Hare
#
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
def solution(head):
cycle_present = False
fast = slow = head
while fast and slow:
slow = slow.next
if fast.next:
fast = fast.next.next
else:
return None
if fast == slow:
cycle_present = True
break
if not cycle_present:
return None
slow = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
# input = [3,2,0,-4]
# root = ListNode(3)
# n1 = ListNode(2)
# n2 = ListNode(0)
# n3 = ListNode(-4)
# root.next = n1
# n1.next = n2
# n2.next = n3
# n3.next = n1
#
# print solution(root).val
root = ListNode(1)
w = ListNode(2)
root.next = w
w.next = root
print solution(root).val