-
Notifications
You must be signed in to change notification settings - Fork 19
/
answer.py
29 lines (24 loc) · 846 Bytes
/
answer.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
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
# We know a linkedList has a cycle if and only if it encounters an element again
if head is not None:
slow = head
fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
if slow is fast:
return True
return False
#-------------------------------------------------------------------------------
# Testing