LintCode Q103 Linked List Cycle II in Python

  • Jinhai ZHOU
  • 4 Minutes
  • 2017年1月19日
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
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: The node where the cycle begins.
if there is no cycle, return null
"""
def detectCycle(self, head):
# write your code here
if head is None or head.next is None:
return
runner = head
current = head
find = False
while runner and runner.next:
runner = runner.next.next
current = current.next
if runner == current:
find = True
break
if find:
current = head
while current != runner:
current = current.next
runner = runner.next
return current
else:
return
知识共享许可协议
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议进行许可。