Given a linked list, determine if it has a cycle in it.
Follow up:
Space: O(1)
Solution
(Linked-List-Cycle.py) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| # 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
"""
if head == None or head.next == None:
return False
slow = head
fast = head.next
while fast != None and fast.next != None:
if slow == fast:
return True
slow = slow.next
fast = fast.next.next
return False
|