Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space.
https://oj.leetcode.com/problems/linked-list-cycle/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param head, a ListNode
# @return a boolean
def hasCycle(self, head):
if head is None:
return False
p = head
q = head
while p is not None and q is not None :
p = p.next
if q.next is None:
return False
q = q.next.next
if p == q :
return True
return False