thiagowfx's avatar

Β¬ just serendipity πŸ€ (not just serendipity)

ByteByteGo: Linked List Loop

β€’ 69 words β€’ 1 min β€’ updated

ByteByteGo: Linked List Loop:

Slow and fast pointers.

python
from ds import ListNode

"""
Definition of ListNode:
class ListNode:
    def __init__(self, val=None, next=None):
        self.val = val
        self.next = next
"""

def linked_list_loop(head: ListNode) -> bool:
    if not head or not head.next:
        return False

    slow = head
    fast = head.next

    while slow != fast:
        slow = slow.next

        if not fast or not fast.next:
            return False

        fast = fast.next.next

    return True