Solution 1
# 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):#the input is head.We do not have pos.
"""
:type head: ListNode
:rtype: bool
"""
s = set()
while head and head.next:
if head in s:
return True
else:
s.add(head)
head = head.next
return False
Time complexity is O(n). Space complexity is O(n).
Solution 2
# 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):#the input is head.We do not have pos.
"""
:type head: ListNode
:rtype: bool
"""
slow, fast = head, head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
Time complexity is O(n). Space complexity is O(1).