1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| struct Node { Node(int x) : val(x) {} Node *next = nullptr; };
Node *getCycle(Node *head) { auto fast = head, slow = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) break; } if (!fast || !fast->next) return nullptr; slow = head; while (slow != fast) { slow = slow->next; fast = fast->next; } return slow; }
bool f(Node *headA, Node *headB) { auto a = getCycle(headA), b = getCycle(headB); if (a && b) return a == b; if (!a && !b) { while (headA != headB) { headA = headA ? headA->next : headB; headB = headB ? headB->next : headA; } return headA; } return false; }
|