அல்கோரிதம்floyd cycle

Floyd cycle — tortoise & hare

TT
Testlaa Team
May 14, 20261 min read

Slow 1, fast 2 — cycle இருந்தால் meet; None — acyclic.

Try this in Python

from __future__ import annotations
from dataclasses import dataclass


@dataclass
class Node:
    val: int
    next: Node | None = None


def to_list(head: Node | None) -> list[int]:
    out: list[int] = []
    while head:
        out.append(head.val)
        head = head.next
    return out


def from_list(vals: list[int]) -> Node | None:
    dummy = Node(0)
    cur = dummy
    for x in vals:
        cur.next = Node(x)
        cur = cur.next
    return dummy.next


def has_cycle(head: Node | None) -> bool:
    slow = fast = head
    while fast and fast.next:
        slow = slow.next  # type: ignore
        fast = fast.next.next  # type: ignore
        if slow is fast:
            return True
    return False

a = Node(1)
a.next = Node(2)
a.next.next = Node(3)
a.next.next.next = a.next
print(has_cycle(a))

Key takeaways

  • while fast and fast.next.
  • Meet — cycle proof.
  • is — node identity.

Tags:

Linked listsPythonமாணவர்கள்