Floyd Cycle Detection Algorithm
อัลกอริทึมตรวจจับ Cycle ใน Singly Linked List เรียกอีกชื่อว่า "Hare and Tortoise Algorithm" (กระต่ายและเต่า)
หลักการ
มี 2 Pointers (Hare และ Tortoise) เริ่มที่ Head:
- Hare วิ่งเร็วกว่า Tortoise 2 เท่า
- เมื่อ Hare ถึงปลายทาง Tortoise จะอยู่กลางทาง
ขั้นตอนอัลกอริทึม
- Initialize Hare และ Tortoise ที่ Head Node
- Hare วิ่ง 2 ก้าว Tortoise วิ่ง 1 ก้าว
- ถ้า Hare ถึง End ของ Linked List → Return "No Loop"
- มิฉะนั้น ทั้งคู่เดินต่อ
- ถ้า Hare และ Tortoise อยู่ Node เดียวกัน → Return "Cycle Detected"
- กลับไปขั้นตอน 2
Pseudocode
tortoise := headNode
hare := headNode
foreach:
if hare == end
return 'There is No Loop Found.'
hare := hare.next
if hare == end
return 'No Loop Found'
hare = hare.next
tortoise = tortoise.next
if hare == tortoise
return 'Cycle Detected'