# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution1(object):
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
result = []
while head:
if head in result:
return True
result.append(head)
head = head.next
return False
class Solution(object):
def hasCycle(self, head):
if not head:
return False
p1 = ListNode(0)
p1.next = head
p2 = head
while True:
if p2 != p1:
p2 = p2.next
if not p2: return False
else:
return True
if p2 != p1:
p2 = p2.next
if not p2: return False
else:
return True
p1 = p1.next
return False
No comments:
Post a Comment