2026/02/22

[LeetCode] 142 Linked List Cycle II

 延續LeetCode 141

先用快慢指針找到相遇點

再從head跟相遇點用一樣速度前進, 就會遇到cycle的進入點


  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* takeOneStep(ListNode *node) {
  12. if (node == nullptr)
  13. return nullptr;
  14. return node->next;
  15. }
  16. ListNode* takeTwoStep(ListNode *node) {
  17. if (node == nullptr)
  18. return nullptr;
  19. ListNode* tmp = node->next;
  20. if (tmp == nullptr)
  21. return nullptr;
  22. return tmp->next;
  23. }
  24. // LeetCode 141. Linked List Cycle
  25. ListNode *foundMeetingPoint(ListNode *head) {
  26. ListNode* stepOneNode = takeOneStep(head);
  27. ListNode* stepTwoNode = takeTwoStep(head);
  28. while (stepOneNode != nullptr && stepTwoNode != nullptr) {
  29. if (stepOneNode == stepTwoNode)
  30. break;
  31. stepOneNode = takeOneStep(stepOneNode);
  32. stepTwoNode = takeTwoStep(stepTwoNode);
  33. }
  34. if (stepOneNode == nullptr || stepTwoNode == nullptr)
  35. return nullptr;
  36. return stepOneNode;
  37. }
  38. ListNode *detectCycle(ListNode *head) {
  39. // Step 1 : find meeting point in cycle
  40. ListNode *meet = foundMeetingPoint(head);
  41. if (meet == nullptr)
  42. return nullptr;
  43. // Step 2 : the middle point of head and meeting point is entry point of cycle
  44. ListNode *start = head;
  45. while(meet != start) {
  46. start = takeOneStep(start);
  47. meet = takeOneStep(meet);
  48. }
  49. return start;
  50. }
  51. };