Linked List Cycle II
Description
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
Challenge:
Follow up:
Can you solve it without using extra space?
Link
Method
- x
- x
Example
- 1
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: The first node of linked list. * @return: The node where the cycle begins. * if there is no cycle, return null */ ListNode *detectCycle(ListNode *head) { // write your code here // test whether it has loop if (!head) { return nullptr; } ListNode* slow = head; ListNode* fast = head->next; while (fast && fast->next) { if (slow == fast) { break; } slow = slow->next; fast = fast->next->next; } if (slow != fast) { return nullptr; } // find cycle point while (head != slow->next) { head = head->next; slow = slow->next; } return head; } };
Similar problems
x
Tags
x