【Lintcode】103.Linked List Cycle II
题目:
Given a linked list, return the node where the cycle begins.
If there is no cycle, return null
.
Example
Given -21->10->4->5
, tail connects to node index 1,return 10
题解:
Solution 1 ()
class Solution { public: ListNode *detectCycle(ListNode *head) { if (!head) { return head; } ListNode* slow = head; ListNode* fast = 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; } };