141. Linked List Cycle
[Easy] “Given a linked list, determine if it has a cycle in it."
Python3:
class Solution:
# def hasCycle(self, head: ListNode) -> bool:
# seen = {}
# next_node = head
# while next_node:
# if seen.get(next_node) != None:
# return True
# else:
# seen[next_node] = 0
# next_node = next_node.next
# return False
def hasCycle(self, head: ListNode) -> bool:
if not head:
return False
slow = head
fast = head.next
while slow != fast:
if not fast or not fast.next:
return False
else:
slow = slow.next
fast = fast.next.next
return True