141. Linked List Cycle
# 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
"""
fast = head
slow = head
while(fast):
if fast.next is None:
return False
fast = fast.next.next # When using linked list, always checking whether each next is valid or not.
slow = slow.next
if fast == slow:
return True
return False
Looping criterion is only related to the fast pointer, since it always meets the end before slow.
There are three conditions to consider:
There is only one node in linked list
There are more than one node and the fast node reaches the final loop:
fast jumps two steps each time, it could be the tail node
Or it could be the tail.next (None)
Note: When using linked list, always checking whether each next is valid or not.
Last updated