// Example: Detecting a cycle in a linked list using fast and slow pointers boolhasCycle(ListNode* head){ if (head == nullptr || head->next == nullptr) returnfalse;
ListNode* slow = head; ListNode* fast = head->next;
while (slow != fast) { if (fast == nullptr || fast->next == nullptr) returnfalse; slow = slow->next; fast = fast->next->next; }
returntrue; }
3. Find the Middle of a Linked List, LeetCode 876
Problem: Given the head of a singly linked list, return the middle node of the linked list. If there are two middle nodes, return the second middle node.
1 2 3 4 5 6 7 8 9 10 11
ListNode* middleNode(ListNode* head){ ListNode* slow = head; ListNode* fast = head; while (fast != nullptr && fast->next != nullptr) { slow = slow->next; fast = fast->next->next; } return slow; // When fast reaches the end, slow will be at the middle }
4. Happy Number, LeetCode 202
A number is considered happy if repeatedly summing the squares of its digits leads to 1. If it enters a cycle that doesn’t include 1, it’s not a happy number.