Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
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
"""
if head is None:
return False
node1 = head
node2 = head
while True:
if node1.next is not None:
node1 = node1.next.next
node2 = node2.next
if node1 is None or node2 is None:
return False
elif node1 == node2:
return True
else:
return False